Question

I've been a little surprised, because I have read before, that __gc metamethod is only called for userdata and never for tables. (LuaFAQ : Why don't the __gc and __len metamethods work on tables?)

But, recently, I have tried it and found it actually works! Try this code with Lua 5.2.1:

do
  local b = setmetatable({a = 1}, {__gc = function(self) print(self.a); end});
end
collectgarbage();

But I can't find anywhere the changelog for this, so I'm little frustrated and afraid to use it.

Maybe, someone can prove my suggestion? Or it is an undocumented behaviour? As for me it will be nice to have a regular way to create table destructor, and I will be glad if my observation is right.

Was it helpful?

Solution

The Lua 5.2 Reference Manual section 2.5.1 indicates that tables do support the __gc metamethod. Specifically, it says

For an object (table or userdata) to be finalized when collected, you must mark it for finalization. You mark an object for finalization when you set its metatable and the metatable has a field indexed by the string "__gc".

The similar documentation in the 5.1 Reference Manual says

Using the C API, you can set garbage-collector metamethods for userdata

It seems pretty clear that Lua 5.2 now explicitly supports the __gc metamethod for tables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top