Lua works with references, apart from some primitives (numbers, booleans and string)
E.g.
local a = {}
local b = a -- just copies the reference
a.ABC = 123
print(b.ABC) --> 123 (a and b are the same thing) (same table in memory)
local player = getPlayer()
local anotherReference = player
-- anotherReference and player point to the same thing in memory
When a function ends, all local variables are removed from the stack, and if the values have no references, they will be (later on, when the next gc cycle hits) garbage collected. The only exception is with upvalues:
function test()
local upval = {}
return function() return upval end
end
local f = test()
-- f is a reference to that returned function
-- since test() ended, the locals get cleaned, but upval is still needed
-- Lua internally moves the upvalue to another place, nothing you should worry about
-- while the "variable" is gone, the table is still in memory (and accessible by f)
local t = f()
-- now we also have a reference to "upval" (not upval, but the table it got set to)
t,f = nil,nil -- set to nil (clear references)
-- f isn't referenced anymore, so it'll be garbage collected soon
-- t is only referenced by f, so once f is gc'd, t/upval can be gc'd too
The player object (and newBlock) objects are never GCed, since you add a reference to them in the table thatâs in collectRequests.
If youâre new to programming, wrapping your head around references and GC is tricky. A good tip for Lua to remember is: If you can access it, it doesnât get GCed (exception: if itâs a weak key/value for weak tables, but eh) e.g. you can access playerWhoTouched/newBlock via collectRequests, so they donât get GCed.
Roblox makes it a bit more tricky with connections: as long as the connection is active (e.g. con.connected
is true, so you didnât call touchConnection:Disconnect()
or newBlock:Destroy()
, itâs (internally) referenced and canât get GCed. The function you connected is also referenced, since it needs to be called when the event fires. All upvalues used by that function also donât get GCed, as the function could use them.
If the above didnât clear it up: That line âcopiesâ the value, but since it isnât a string/number/boolean, it actually copies the reference. Both point to the same player object, which wonât get GCed.
TL;DR and actual answer to your question:
The playerWhoTouched variable is removed when the function ends. Youâre storing a reference to the actual Player object in the table, not a reference to the variable (thatâs impossible in Lua), so the player object wonât get GCed