i mean, it doesn't really matter in this case, but it does matter when you have nested loops and events...'
when you do object.EventName:Connect(f)
where f
is a function, the Roblox event loop stores the function and calls it whenever the event occurs.. and therefore you only have a single function in memory..
but when you have nested loops, its best to put a function in a variable, other wise the loop will keep allocating memory with each iteration.. for example:
1 | local Players = game.Players |
2 | local players = Players:GetChildren(); |
4 | for _, player in pairs (players) do |
5 | player.SomeEventName:Connect( function () |
6 | print ( "Something happened" ) |
if the above code ran when there is 30 players in the server, it means Lua will allocate memory for 30 functions, because on each iteration we call Connect()
with a new function.. the more memory we allocate, the less memory we have to run other things, and the poor the performance of our game.. and that's what we call a Memory leak
so in this case, it would be a great idea to put a a function in a variable, and just pass that one function to each call to Connect()
.. here is the same, but efficient version of the above code
01 | local Players = game.Players |
02 | local players = Players:GetChildren(); |
04 | function onSomeEventName() |
05 | print ( "something happened" ) |
08 | for _, player in pairs (players) do |
09 | player.SomeEventName:Connect(onSomeEventName) |
in this version, all the calls to player:Connect
are passed a single function, and therefore, only 1 memory allocation is done for the connecting functions..
remember, every variable that we create takes up memory, therefore, only declare variables when you'll only need them.. for example:
variables that you will use in a function
should be declared in a function..
whenever a function
returns, Lua will automatically return the memory it allocated, giving us more memory to do more things, whenever you set a variable to nil
it also helps in returning memory..