Вопрос

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
Это было полезно?

Решение

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.

Другие советы

All is about references. Even if you have setted to nil a variable that references a table if there is another reference to the table the Garbage Collector doesn't free memory. Because table is still "in use".

Ex:

myTable = {}
myOtherTable = myTable
for n=1,5 do
    local item = {
        name = "item"..n,
        id = n,
    }
    myTable[n] = item
end

print(myTable)
myTable=nil
print(myTable)
print(myOtherTable)

--OUTPUT
--table: 0x8ebb40
--nil
--table: 0x8ebb40

If a table is referenced anywhere (even inside another table) it isn't freed.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top