can't destroy object

Hi,

I have simply object for example st=Star(100,100) and when I use st=nil object still exist. Can someone help me how to figure out this? Thanks

How do you know that the object still exists? There are no destructors to tell you about this.

There are some reasons why an object is not destroyed if you assign nil to a variable. If you say st=nil then you simply tell the interpreter that you don’t longer need st, you can forcibly run the garbage collector to destroy it (or is it actually destroyed upon setting it to nil but simply not removed from memory?).

Also, if you have other references to the object it will not be destroyed as well.


st = Star(100, 100)
-- hidden somewhere else
st2 = st
-- Attempt to destroy the "original" object
st = nil

The object will continue to exists because st2 points to it.

I know it becouse it drawing on screen. Here is class Star.

Star = class()
function Star:init(x,y)
     self.x=x
     self.y=y
end

function Start:draw()
     sprite("star",self.x,self.y)
end

When I use st=Star(100,100) and then print(st), it print table. After st=nil commant it print nil but object still exist. I am sure that there are not any references to this object.

It is drawing on the screen? Better to say that it is being told to draw by some code because it doesn’t magically draw itself. Some part of the code must know the object and is able to draw it. I assume your code is made up of elements similar to these:


function setup()
    st = Star(100, 100)
    objectToDraw = st
end

function draw()
    objectToDraw:draw()
end

function kill()
    st = nil
end

Let’s make it clear, st is not the object itself, st is a reference to an object. If st is the only reference then you may think of it as really being the object because of the 1:1 relation; however, technically st is only a pointer to the real object. In the code above, when I state objectToDraw=st, then objectToDraw is another pointer to the very same object. When you say st=nil then you only remove a pointer, you remove one thing that knows about the object, but another thing still remembers it, therefore the object lives on.

If you’re drawing it then you’re naming it; if you can name it, you remember it; if you remember it, it is not destroyed.

(There are exceptions, but they don’t apply here.)