问题描述
我有以下Lua元表类,如何向其添加析构函数,以便在达到特定条件时它将析构创建的对象并将其值设置为nil?
I have the following Lua metatable class, how can I add a destructor to it so when a certain condition arrives it will destruct the created object and set it's value to nil?
-------------------------------------------------
-- Arrow class
-------------------------------------------------
local arrow = {}
local arrow_mt = { __index = arrow } -- metatable
function arrow.new(x, y) -- constructor
local newArrow = {
position = { x = x, y = y }
}
return setmetatable( newArrow, arrow_mt )
end
function arrow:remove()
-- remove the object here
-- self = nil dosent work
end
推荐答案
正如Nicol所说,一旦变量获得对您对象的引用,对象本身就无法控制该变量(即,将其值设置为 nil ).实际上,这是一件好事-假设某人在某个地方保存了对您的引用,但该对象指向局部变量.突然在一个未知的时刻,它变成了一个 nil 引用(因为它在其他地方被销毁了),任何对其的进一步访问都将导致错误.
As Nicol said, once a variable gets a reference to your object, the object itself cannot control the variable (i.e. set it's value to nil). Actually, this is a good thing - imagine someone somewhere saved a reference to you object to a local variable. Suddenly at an unknown moment, it becomes an nil reference (because it is destroyed somewhere else), and any further access to it results in an error.
您真的需要销毁该物体吗?为什么? Lua垃圾收集器执行不正确吗?还有没有其他方法可以设计对象之间的关系?
Do you really need to destroy the object? Why? Isn't the Lua garbage collector doing it's job correctly? Isn't there another way to design the relationship between the objects?
例如,在最简单的情况下,您可以通过collectgarbage("collect")
强制进行垃圾回收.垃圾回收将清除所有没有 strong 引用的对象.如果您真的希望变量消失,请将其保留在弱表中.当然,Lua会在分配对象时自动进行垃圾收集(除非您停止它).您也可以修改垃圾收集的速度.
For example, in the simplest case, you can force a garbage collection through collectgarbage("collect")
. A garbage collection will clean all objects, that have no strong references to them. If you really want variables to disappear, keep them in a weak table. Of course, Lua will do the garbage collection automatically while you allocate objects (unless you stop it). You can also modify the speed of garbage collection.
这篇关于Lua可继承类的析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!