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:
local Players = game.Players
local players = Players:GetChildren();
for _, player in pairs(players) do
player.SomeEventName:Connect(function()
print("Something happened")
end)
end
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
local Players = game.Players
local players = Players:GetChildren();
function onSomeEventName()
print("something happened")
end
for _, player in pairs(players) do
player.SomeEventName:Connect(onSomeEventName)
end
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..
1 comment
in the function, how would you reference "player" in the for loop?