Lua metatable class destructor

2019-07-17 06:26发布

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

2条回答
▲ chillily
2楼-- · 2019-07-17 06:35

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.

查看更多
Ridiculous、
3楼-- · 2019-07-17 06:40

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.

查看更多
登录 后发表回答