Destructors in Lua?

2019-03-19 08:52发布

问题:

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!

回答1:

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.