Two onPlayerDeath functions

Started by habi, Mar 14, 2023, 05:47 PM

Previous topic - Next topic

habi

Suppose you are publishing a script.
This is an example to show you how to attach your onPlayerDeath event to other scripter's onPlayerDeath function.
Usually we do this by instruction to 'add codes' to user's main.nut at different places.
This method hooks the original event, then calls it and then calls 'your' function and can return either the return value of original event or return value of 'your' function.
yourcode.nut
{
    local MyonPlayerDeath=
    function (player, reason)
    {
        if(player.Cash >= 1000 )
        player.Cash -= 1000;
        print("Custom onPlayerDeath executed");
    }
    if(rawin("onPlayerDeath")&&typeof(rawget("onPlayerDeath"))=="function")
    {
        local onPlayerDeathOriginal=rawget("onPlayerDeath");
        onPlayerDeath<-
        function(player, reason)
        {
            local retval = onPlayerDeathOriginal(player, reason);
            MyonPlayerDeath(player, reason);
            return retval;
        }
    }else
    {
        onPlayerDeath<-MyonPlayerDeath;
    }
}
The above script decreases cash of player by 1000 when the player dies. The original onPlayerDeath function will also be called (first).
So we have achieved something without telling the scripter 'add this line to your onPlayerDeath'.