- Joined
- Feb 14, 2015
- Messages
- 5,643
- Solutions
- 559
- Reaction score
- 3,953
This provides a safe way to use addEvent with userdata without having to manually reconstruct the object yourself in order to avoid crashes. If the object can't automatically be reconstructed at the time of execution, it will not execute at all. The usage is the same as the normal addEvent.
Examples of this:
Code:
Everything written on my phone, hopefully no syntax errors.
Examples of this:
safeAddEvent(Player.addHealth, 3000, Player('Delusion'), 100)
safeAddEvent(Player.sendTextMessage, 1000, Player('Delusion'), MESSAGE_INFO_DESCR, 'Test')
Code:
Lua:
function safeAddEvent(f, interval, ...)
local convertedArgs = {}
for k, arg in ipairs({...}) do
if type(arg) == 'userdata' then
local convertedArg = {args = {arg:getId()}}
if Player(arg) then
convertedArg.constructor = Player
elseif Monster(arg) then
convertedArg.constructor = Monster
elseif Npc(arg) then
convertedArg.constructor = Npc
elseif arg:isItem() then
local parent = arg:getTopParent()
if parent:isTile() then
convertedArg.args = {arg:getPosition(), arg:getId()}
convertedArg.constructor = function(pos, itemId)
local tile = Tile(pos)
if tile then
return tile:getItemById(itemId)
end
end
end
end
convertedArgs[k] = convertedArg.constructor and convertedArg or arg
else
convertedArgs[k] = arg
end
end
local function callback()
local parsedArgs = {}
for k, arg in ipairs(convertedArgs) do
if type(arg) == 'table' and arg.constructor and arg.args then
local obj = arg.constructor(unpack(arg.args))
if not obj then
return nil
end
parsedArgs[k] = obj
else
parsedArgs[k] = arg
end
end
f(unpack(parsedArgs))
end
return addEvent(callback, interval)
end
Everything written on my phone, hopefully no syntax errors.
Last edited: