When I do a FireServer with a table containing functions as a parameter, the server script doesn't receive the functions.
Example :
Local script :
local test = { text = "text"; function1 = function() print("function1") end; } local re = game.ReplicatedStorage:WaitForChild("RemoteEvent") re:FireServer(test)
Server script :
game.ReplicatedStorage.RemoteEvent.OnServerEvent:Connect(function(player, test) print(test.text) test.function1() end)
It does print the text, but it is unable to find the function.
The error message is : attempt to call field 'function1' (a nil value)
Am I doing something wrong? If not, is there a way to avoid this problem?
Functions cannot be passed through remotes; if an attempt is made, the receiving remote will simply receive the argument as nil
. There at least two workarounds for this issue:
Both of these solutions require you to define the functions on the receiving end:
-- Client: remote_event:FireServer("func1") -- Server: local funcs = {} function funcs.func1() print("func1") end function funcs.func2() print ("func2") end -- ... remote_event.OnServerEvent:Connect(function(player, func) local f = funcs[func] if not f then return end f() end)
This is just an update to what Dandystan has posted. It is very common for you to need to pass arguments in a remote and you can use ...
Variable Number of Arguments.
Example:-
-- Client: remote_event:FireServer("func1", "hi") -- prints func1 hi remote_event:FireServer("func1", "hi", "hi2") -- prints func1 hi remote_event:FireServer("func2", "hi") -- prints func2 hi nil remote_event:FireServer("func2", "hi", "hi2") -- prints func2 hi hi2 -- Server: local funcs = {} function funcs.func1(arg) print("func1", arg) end function funcs.func2(arg1, arg2) print ("func2") end -- server remote_event.OnServerEvent:Connect(function(player, func, ...) --- ... varargs if funcs[func] then funcs[func](...) -- pass args over to the function end end)
Look into ModuleScripts. I've found them very helpful. Store your functions in the module. Unsure if this will help you though. If you dm me on Discord, I can help you better. Bark#4492. I'm in the SH discord.