Function as argument
hi guys
i could made a method that help lua to pass a function as argument and send it to other resources
and you can use it in both server and client sides
you can pass function as argument in triggerEvent or exports.resource:func_name or setElementData(if you set 4th argument to false) and send it to another resource and call it
and also you can send functions in table (but you can't share metamethods)
for example:
-- resource : A
local player = nil;
local library = {};
function library.SetPlayer(element)
if isElement(element) then
player = element;
end
end
function library.GetPlayer()
return player;
end
addEvent("getlibrary", false);
addEventHandler("getlibrary", localPlayer, function(send)
iprint("function is:", send, type(send)); -- type(send) = table
send(library);
print("library sent to ", getResourceName(send.resource));
send:free(); -- cleanup function reference at resource B (this cleans up the memory. if you don't call this method it stays in memory untill program destroy lua stack like stopping resource)
end);
-- resource : B
local library;
triggerEvent("getlibrary", getLocalPlayer(), function(resourceALibrary)
library = resourceALibrary;
print("resource B got the library!");
end);
if library then
print("player is : ", library.GetPlayer()); -- nil
library.SetPlayer(getLocalPlayer());
print("player is : ", library.GetPlayer()); -- local player
end
when you pass a function as an argument it will look like a table and has these values: -- function reference: .resource : the resource that owns function .reference : the reference id .free : this method deletes the reference. if you call it, means that you won't be able to use that function anymore
note 1 : you can store a function reference in other resource if you want to let it be active otherwise if you call that function in render event or sth like that and you don't use :free method, after seconds your game or server console crashs because it occupies your memory
note 2 : remember when you want to cleanup your function call it as method, like function:free (not like function.free) because free needs a callable value as first argument
couldn't you just implicit convert functions to refs using ref and deref
couldn't you just implicit convert functions to refs using
refandderef
i think i couldn't understand well what you mean but if you mean why those are table its because it doesn't cause confusion when passing a function as an argument in triggerEvent and other functions and you can check in other resources that where does this function come from
No news about this PR? I can't imagine a cases for what need store functions in elementData, but for exports it very useful. 🤔
This reminds me of #3551