开发者

Destructors in Lua?

开发者 https://www.devze.com 2023-01-04 14:44 出处:网络
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.

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 fun开发者_如何学Goction called when a table is collected.

Thanks!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消