Cleanup/Destroy/Finalise - How do YOU do it?

I’m from a C#/Java background and am used to handling complex object destruction/memory cleanup by providing a ‘destructor’ - the opposite of a constructor - in order to cleanup any mess when an object is (about to be) removed from memory.

I was reading this: http://developer.anscamobile.com/content/introduction#Memory_Allocation

While I see that garbage collection is handled quite nicely by ‘= nil’ and in the case of display objects the necessary ‘removeSelf()’ to remove the final (graphics memory) reference to an object, there is one problem…

I have a display object (in this case, a group) on which I have a repeating timer. Every 250 milliseconds this timer calls a specific function on the object. This is fine.

The problem is that when I garbage collect the object, the timer still fires because it has not been cancelled. This results in trying to reference (often un-forseeablly) nil objects and, therefore, exceptions.

My question is: Is there a lua version of the ‘desctructor’ or ‘finalizer’? Basically, a function which can be called automatically when an object’s reference is set to nil (I don’t see this happening, tbh) OR perhaps the ability to override functions like ‘removeSelf()’ so that my version of ‘removeSelf()’ gets called, does it’s timer cancelling and then calls the original (display group’s) ‘removeSelf()’?

Or, how do you do it?

The option on the table at the moment is simply to have my own remove() function, which subsequently calls ‘removeSelf()’, it just seems untidy.

Sorry for the ramble, thanks for any info…

Matt. [import]uid: 8271 topic_id: 5191 reply_id: 305191[/import]

I have faced similar situations in the past. I managed to get around it by:

  1. Creating my own functions to add and remove timers/events which are stored in a lookup table. The timer/event is removed immediately by calling my function before object is nilled.

  2. Each display object is in a table or reference variable which is nil checked inside the timer/event. I have my own functions to create/destroy display groups which are all referenced inside a table.

My next step is to link the display object and event tables together. So I will call my own function destroy( object ) it will check the lookup table to see if a timer/event is attached to the object and then destroy it. But that’s in my “roadmap” after a bunch of other things.

[import]uid: 11393 topic_id: 5191 reply_id: 17228[/import]

The option on the table at the moment is simply to have my own remove() function, which subsequently calls ‘removeSelf()’, it just seems untidy.

This is how I do it, because I don’t think Lua has destructors. Now I’m curious though if Lua has destructors. [import]uid: 12108 topic_id: 5191 reply_id: 17244[/import]

On one hand it would seem obvious not to, but on the other, it would be handy to have a standard cleanup operation. [import]uid: 8271 topic_id: 5191 reply_id: 17258[/import]