fivem
fivem copied to clipboard
Unintuitive scripting behavior: source variable in Lua becomes nil if any time passes during event handler
When a server event handler is being run, the source variable thats inherently provided becomes nil if any time passes i.e Wait()'ing
This is confusing behavior and presumably not intended
it can be worked around by simply defining a second variable and setting it to the value of source at the beginning but is obviously not ideal
Repro code:
CLIENT:
RegisterCommand("sourcerepro", function(source, args, raw)
TriggerServerEvent("reproevent")
end)
SERVER:
RegisterNetEvent("reproevent")
AddEventHandler("reproevent", function()
print(source)
Wait(0)
print(source)
end)
It's not bug, the source variable is defined in scheduler.lua as global variable https://github.com/citizenfx/fivem/blob/71a593bd93635f1434d1e9b7b759e634d5ec77ef/data/shared/citizen/scripting/lua/scheduler.lua#L156-L159
So, you can simply use:
local src = source
at top of event handler to use event source after wait
It's not bug, the source variable is defined in scheduler.lua as global variable
https://github.com/citizenfx/fivem/blob/71a593bd93635f1434d1e9b7b759e634d5ec77ef/data/shared/citizen/scripting/lua/scheduler.lua#L156-L159
So, you can simply use:
local src = source
at top of event handler to use event source after wait
Noted, i figured this was some weird behavior but seeing how that works now makes sense and any alternative would not be within the realm of easy fixing. Closing
This is still somewhat illogical behavior, but somehow dynamically adding upvalues for a handler sounds like a potential mess (and requiring the lexer/parser to be aware of this beforehand, even).
A similar alternative could be something like the .NET SynchronizationContext where state like 'source' is saved and restored when yielding with such set.