How to get an instance of a class to delete itself (solved)

Sorry there was a previous thread for this but I couldn’t find it with a forum search

@Coder You should be able to assign nil to the instance variable.

@dave1707 sorry I should have been more clear. I meant is it possible to call to delete the instance inside the class code. Thanks anyway though.

Got it now.

Self.num = position in table 

@Coder this doesnt look like what you requested for. I thought you wanted to delete an instance of the class from the instance itself, like self:delete(). This is not possible in general, but there are various way to store your instances that can give this result.

For example: store all your instances in a table t: t[1]=inst1, t[2]=inst2, … etc, and nowhere else. then if your self:delete() method knows t , it can delete itself the way you described it above. Note that the instance will not be deleted immediatly, but next time collectgarbage() is called (this may take seconds).

(looks like i understood your post only at the end of mine :wink: )

@Jmv38 thanks that should work

If you can’t store all your instances in a table (if you have a tree, for example), you can try something like

self.parent.children = nil

assuming of course that you have passed a pointer of the parent to the object, for example in the init function.

@RyZum thanks