1
votes

Here is my test code :

mt={}
myt={}
setmetatable(myt, mt)
mt.__gc=function()print("hello gc")end
myt=nil
collectgarbage()

But, when i running this code, there's no message print.

So, I think there must something wrong in my code.

Update:

mt.__gc=function()print("hello gc")end
setmetatable(myt, mt)

Set __gc field before setmetatable would solve the question(using the online interpreter), but, when I executing the same code through C API luaL_dofile in my program, __gc is dead again.

And I also test in my standalone lua interprete(lua 5.1.5), and '__gcc' is dead too.

The only working fine case is that online interpreter which version is 5.3.

So, I should probably ask how can I get '__gc' to work under my 5.1 version ?

1
__gc metamethod should be in metatable when you call setmetatable. And ofcourse it works only since Lua 5.2 - moteus
setmetatable({}, {__gc = function() print("hello gc") end}) collectgarbage() Tested on Lua 5.2 - moteus
Thanks a lot @moteus.BUT WHY?Because, when I set other elements of the metatable after I call 'setmetatable' , they all work fine, such as __index, some functions, variables...Why "GC" so special?Is there any official doc telling about this? - Francis
Yes, I have found this note.But, I still can not run this code correctly in my 'luaL_dofile' c api case.Is there any other note should I have to know in my case?@moteus - Francis

1 Answers

1
votes

You need to set the __gc field before calling setmetatable.

The manual says:

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.

GC methods for tables were introduced in Lua 5.2. They don't work in Lua 5.1.