R – Lua garbage collection of Tables, nested Tables

lualua-tablememory-management

[I've read the Lua manual, but it did not provide solid answers.]

Let's say I have a Lua Table, acting as an indexed array:

local myArray = {};
myArray[1] = "Foo";
myArray[2] = "Bar";

How do I best dispose of this Table? Do I just set myArray to nil? Or do I have to iterate through array and set each indexed element to nil?

Similarly, let's say I have I have a Lua Table, acting as a dictionary:

local myDictionary = {};
myDictionary["key1"] = "Foo";
myDictionary["key2"] = "Bar";

Can I just set 'myDictionary' to nil, or do I have to iterate through?

Lastly, what do I do, memory-management wise, where I have nested Tables? e.g.

local myNestedCollection = {};
myNestedCollection[1] = {1, 2, 3};
myNestedCollection[2] = {4, 5, 6};

Do I need to iterate through each of these sub-tables, setting them to nil? Thanks for any help.

Best Answer

In most GC an object will be collected when there are no references to it. Setting the top of your reference chain to nil removes a reference to the children. If that was the only reference then the children will be collected.

Related Topic