tags:

views:

119

answers:

1

Is it possible to get destructors in Lua w/o using userdata?

http://www.lua.org/notes/ltn006.html looks promising (in fact exactly what I want); except it's a path for Lua 4.0.

Basically, I want a way to have a function called when a table is collected.

Thanks!

+4  A: 

From the documentation on metatables:

A metatable may control how an object behaves in arithmetic operations, order comparisons, concatenation, length operation, and indexing. A metatable can also define a function to be called when a userdata is garbage collected.

The Lua Users' Lua FAQ states:

Why doesn't the __gc and __len metamethods work on tables?

Userdata objects frequently require some explicit destructor to run when the object is about to be deleted, and Lua provides the __gc metamethod for that purpose. However, this is not allowed on tables for efficiency.

Normally, there is no need to set a destructor on a table, since the table will be deleted automatically, and any references the table contains will then be garbage collected normally. A possible workaround is to create a userdata; make the table the userdata's environment table, and place a reference to the userdata in the table. (Make sure that this is the only reference to the userdata.) When the table becomes collectable, the userdata's __gc metamethod will be run; Lua will not actually destroy the table before that happens because the table is referenced by the userdata.

So there you go, you will have to manually wrap your tables in userdata if you want to get the __gc event.

Mark Rushakoff