问题描述
是否可以使用userdata在Lua w/o中获得析构函数?
Is it possible to get destructors in Lua w/o using userdata?
http://www.lua.org/notes/ltn006.html 外观承诺(实际上正是我想要的);除了它是Lua 4.0的路径.
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.
谢谢!
推荐答案
来自元表:
Lua用户的Lua常见问题解答指出:
The Lua Users' Lua FAQ states:
通常,无需在表上设置析构函数,因为该表将被自动删除,并且该表包含的所有引用都将被正常垃圾回收.一个可能的解决方法是创建一个用户数据.使该表成为用户数据的环境表,并在该表中放置一个对用户数据的引用. (确保这是对userdata的唯一引用.)当表变为可收集表时,将运行userdata的__gc
元方法;否则,该方法将运行. Lua实际上不会在此之前销毁该表,因为该表已由userdata引用.
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.
因此,如果要获取__gc
事件,则必须手动将表包装在userdata中.
So there you go, you will have to manually wrap your tables in userdata if you want to get the __gc
event.
这篇关于Lua的破坏者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!