Hello experts and curious readers.
I am trying to find a way to force all display objects to automatically post an event just prior to removal.
My purpose in doing this, is to enable easy destruction and cleanup in cases where it is essential that certain actions occur just prior to the removal of an object.
Clarification on the term ‘Removal’
For me, the words remove and destroy when referring to a display object are synonymous. I am referring to the point in time when Corona removes that object from the processing and rendering pool and hands over management of the left-over stuff to Lua.
In Corona SDK, object destruction (as I understand it) can be broken down into two major phases:
- Remove Corona bits and stop processing and rendering the object. Leaves a Lua Table stub behind. ( I only care about this part. )
- Remove the Lua table stub and schedule it for garbage collection at a future date. At this point the object is completely gone.
Assuming I have this code,
local myGroup = display.newGroup() local myCircle = display.newCircle( myGroup, 240, 160, 30 ) myCircle.onRemove = function( self, event ) -- Do something here end
the object ‘myCircle’ can be removed in each of these ways:
-- 1. removeSelf() on the object. -- myCircle:removeSelf() -- 2. display.remove() the object. -- display.remove( myCircle ) -- 3. removeSelf() on group containing the object. -- myGroup:removeSelf() -- 4. display.remove() group containing the object. -- display.remove( myGroup ) -- 5/6. - Storyboard and Composer removals. -- -- For storyboard or composer, if the group 'myGroup' (which contains 'myCircle') -- was added to the scene's group, 'myGroup' and 'myCircle' will be removed -- when the scene is destroyed. -- 7. - App/Game destruction. -- -- When the app is killed/stopped/destroyed the group and object will also -- be destroyed
The Behavior I’m Looking For (Trying to Create)
In each of the above cases, I would like to find a way to have the method ‘onRemove()’ get called automatically just prior to the removal. The key here is that I’d like this to be automatic.
I am considering filing a feature request to add new Corona event like ‘touch’, ‘collision’, etc that will fire just prior to destruction.
However before I do that, I’d like to use your brain and see if anyone knows of a way to do this now. My thought is that there may be a way to make this happen with Lua metatable programming. Unfortunately, all my efforts to date have failed.
So, after that long soliloquy, if you have any suggestions, ideas, or questions please post them below.
Thanks!
Ed M.