简体   繁体   English

Lua __gc元方法现在可用于表(Lua 5.2.1)吗?

[英]Does Lua __gc metamethod now work for table (Lua 5.2.1) ?

I've been a little surprised, because I have read before, that __gc metamethod is only called for userdata and never for tables. 我一直有点惊讶,因为我已经阅读之前,即__gc元方法只要求用户数据和从不为表。 ( LuaFAQ : Why don't the __gc and __len metamethods work on tables? ) LuaFAQ:为什么__gc和__len元方法不能在表上使用?

But, recently, I have tried it and found it actually works! 但是,最近,我尝试了一下,发现它确实有效! Try this code with Lua 5.2.1: 使用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. 对于我来说,有一种常规的方法来创建表析构函数将是很好的,如果我的观察正确的话,我将感到高兴。

The Lua 5.2 Reference Manual section 2.5.1 indicates that tables do support the __gc metamethod. Lua 5.2参考手册的2.5.1节指出表确实支持__gc元方法。 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". 当您设置对象的元表并且该元表具有由字符串“ __gc”索引的字段时,您会将对象标记为最终确定。

The similar documentation in the 5.1 Reference Manual says 5.1参考手册中的类似文档说

Using the C API, you can set garbage-collector metamethods for userdata 使用C API,您可以为userdata设置垃圾收集器元方法

It seems pretty clear that Lua 5.2 now explicitly supports the __gc metamethod for tables. 显然,Lua 5.2现在明确支持表的__gc元方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM