Lua metatable class destructor

核能气质少年 提交于 2019-12-14 02:18:25

问题


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

回答1:


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.

That's a bummer, I need the object destroyed right away.

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?

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.




回答2:


You can't. Lua isn't C/C++; it uses garbage collection. You therefore have to rely on garbage collection; the user of your object has control over when it goes away. It is up to them to discard their references to it when they're done with it.

So while you can have an explicit "new" (though you shouldn't call it that), you don't get to have an explicit "delete". Destruction will happen when the object is no longer referenced.



来源:https://stackoverflow.com/questions/8392168/lua-metatable-class-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!