in Lua, should I assign all table element to nil when it's not used?
garbage-collection, lua, lua-table, memory-leaks
Solution
Simply assign `myTable = nil` is fine. You can test it like this, using the `__gc` metamethod:
myTable = {}
for n=1,5 do
local item = {
name = "item"..n,
id = n,
}
setmetatable(item, {__gc = function (self) print("item " .. n .." collected") end})
myTable[n] = item
end
myTable = nil
collectgarbage()
Output:
item 5 collected
item 4 collected
item 3 collected
item 2 collected
item 1 collected
This means all the `item` tables are collected by the garbage collector.
Problem
For example, I have created a table this way ``` myTable = {} for n=1,5 local item = { name = "item"..n, id = n, } myTable[n] = item end ``` When this table is no longer used, in order to release this table for the garbage collector, do I need to loop through the table to assign each element to nil? ``` for n=1,5 myTable[n] = nil end ``` or all I just need to do is to assign the table to nil? ``` myTable = nil ``` On addition to the above, what if the table element has some property that is assigned to some other table, do I need to nil them individually too? ``` for n=1,5 myTable[n].someTable = nil myTable[n] = nil end myTable = nil ```