If I want to get rid of an object once and for all, can I just say:
self = nil
I trying this, but as far as I can tell, the object is still there. Is there anything else I can do to banish an object, so to speak?
If I want to get rid of an object once and for all, can I just say:
self = nil
I trying this, but as far as I can tell, the object is still there. Is there anything else I can do to banish an object, so to speak?
This will work — however self
is a special object.
For example, you might have method declared as follows:
function MyClass:myFunction(x, y, z) self.pos = vec3(x,y,z) end ------------------ -- calling the method obj = MyClass() obj:myFunction( 1, 2, 3 ) ``` In the context of the method function (i.e. `function MyClass:myFunction`) the keyword `self` is really referring to an argument. So setting it to nil will not really do anything. E.g., the above code is similar to the following:-- Notice how "self" is an argument -- and the function is declared with a '.' function MyClass.myFunction(self, x, y, z) self.pos = vec3(x,y,z) end ------------------ -- calling the method -- notice we pass 'obj' as the argument for 'self' obj = MyClass() obj.myFunction( obj, 1, 2, 3 ) ``` So, if you really want to delete the object represented by `self`, set the actual object to `nil` — not `self`.
Here is a small example of destroying an object and setting it to nil. This draws a falling circle and when it reaches a y value of 300, the circle is destroyed.
function setup()
c1=circle(400,800)
end
function draw()
background(40, 40, 50)
c1:draw()
end
circle=class()
function circle:init(x,y)
self.c1=physics.body(CIRCLE,50)
self.c1.x=x
self.c1.y=y
end
function circle:draw()
fill(255)
if self.c1~=nil then
ellipse(self.c1.x,self.c1.y,100)
if self.c1.y<300 then
self.c1:destroy()
self.c1=nil
end
end
end
@Simeon thanks for explaining the keyword ‘self.’ It makes more sense now. At the end of your post you mentioned that I should delete the object represented by self. I’m not quite sure how to do this.
*For clarifation of my question, I don’t want to delete the whole class, just one item that is made from that class.
So in that case you could do it like this:
obj = MyClass() obj:myFunction( 1, 2, 3 ) -- Later on... obj = nil -- deletes 'obj' ``` Setting an object to nil will not delete it immediately, but it will delete it next time the garbage collection process is run.