Lua的破坏者? [英] Destructors in Lua?

查看:69
本文介绍了Lua的破坏者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用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.

谢谢!

推荐答案

来自元表:

元表可以控制对象在算术运算,顺序比较,串联,长度运算和索引编制中的行为.当用户数据被垃圾回收时,元表还可以定义要调用的函数.

A metatable may control how an object behaves in arithmetic operations, order comparisons, concatenation, length operation, and indexing. A metatable can also define a function to be called when a userdata is garbage collected.

Lua用户的Lua常见问题解答指出:

The Lua Users' Lua FAQ states:

为什么__gc和__len元方法不能在表上使用?

Userdata对象在要删除对象时经常需要运行一些显式的析构函数,而Lua为此提供了__gc元方法.但是,出于效率考虑,这在表格上是不允许的.

Why doesn't the __gc and __len metamethods work on tables?

Userdata objects frequently require some explicit destructor to run when the object is about to be deleted, and Lua provides the __gc metamethod for that purpose. However, this is not allowed on tables for efficiency.

通常,无需在表上设置析构函数,因为该表将被自动删除,并且该表包含的所有引用都将被正常垃圾回收.一个可能的解决方法是创建一个用户数据.使该表成为用户数据的环境表,并在该表中放置一个对用户数据的引用. (确保这是对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的破坏者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆