views:

509

answers:

2

[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.

+4  A: 

It should be sufficient just to set the local variable to nil; there's no need to iterate through all of the keys and set them to nil to. According to this page, Lua uses a mark-and-sweep garbage collection algorithm. As soon as you set your local variable to nil, the keys in its table become unreachable, so they will be collected by the garbage collector on the next collection. Similarly, if those objects are also tables, their keys will also become unreachable, so they too will be collected.

Adam Rosenfield
+5  A: 

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.

SpliFF
Thanks to both SpliFF and Adam for your help with this.
SirRatty