这是我的测试代码:
mt={}
myt={}
setmetatable(myt, mt)
mt.__gc=function()print("hello gc")end
myt=nil
collectgarbage()
但是,当我运行此代码时,没有消息打印。
所以,我认为我的代码一定有问题。
更新:
mt.__gc=function()print("hello gc")end
setmetatable(myt, mt)
在 setmetatable
之前设置 __gc
字段可以解决问题(使用在线 interpreter ),但是,当我执行相同的代码时通过我的程序中的 C API luaL_dofile
,__gc
又死了。
我还在我的独立 lua 解释器(lua 5.1.5)中进行了测试,并且 '__gcc' 也死了。
唯一工作正常的情况是在线 interpreter哪个版本是5.3。
那么,我可能应该问如何让“__gc”在我的 5.1 版本下工作?
最佳答案
您需要在调用 setmetatable
之前设置 __gc
字段。
manual说:
Note that if you set a metatable without a
__gc
field and later create that field in the metatable, the object will not be marked for finalisation.
Lua 5.2 中引入了表的 GC 方法。它们在 Lua 5.1 中不起作用。
关于lua - 如何显式调用lua gc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41117629/