How to get an instance of a class to remove itself.

I’m looking for a way to have an instance of a class destroy itself by calling it’s own method :destroy() I’ve stumped myself. Any ideas how this could be done. I found TLL’s implementation of class() can could modify it but I’d rather not. Any ideas?

The instance is removed at garbage collection when there are no references to it, to do it manually your destroy method could remove the relevant information but your class methods need to be aware of that the object is destroyed. do you have some example code of what you want to achieve?

@tnlogy - I think this example is what he means

g = myClass()

--much later, inside this same instance of myClass
--how can it destroy itself or set g to nil?
--it doesn't know that it has been assigned to g so it can't say g=nil

@tnlogy I’ve just been playing around trying to figure it out. Basically I want to do this:

Foo = class()

function Foo:init()

end

function Foo:destroy()
self = nil --this doesnt work
collectgarbage()
end

function setup()
foo = Foo()
--do stuff
foo:destroy()
print(foo) --nil
end

I realize I could just do foo = nil but I’d like to do it from inside it’s own instance.

You cant do it. You would need something like the become operator in SmallTalk.

http://gbracha.blogspot.se/2009/07/miracle-of-become.html

You cant know how many references you have to an object, references are one-way. Figure out some other way to solve it. :slight_smile:

function setup()
    a = Obj()
    print(a)
    a:destroy()
    print(a)
end

Obj = class()

function Obj:init()
    self.msh = "created"
end

function Obj:destroy()
    local l = 0
    local e
    repeat
        e = getfenv(l)
        for k,v in pairs(e) do
        print(k)
            if v == self then
                print("Found it at level " .. l)
                e[k] = nil
            end
        end
    l = l + 1
    until e == _G
end

maybe I should say you cant do it efficiently :slight_smile:

would that work if the object is an argument to a closure for a function that is a callback to http.request for example? no reference to it from the global scope?

lol @Andrew_Stacey is a Jedi Master.

However I think I’ll stick to instance = nil. It was just one of those things I wanted to see done.