Proper Group Cleaning in Corona (Script Download)
The other day I was browsing the Corona forums to see if I could help anyone out who hadn’t already been helped, and I stumbled upon a thread where a particular member was confused as to why all of the children display objects in a group weren’t being removed when
removeSelf() was being called on the parent group.
I replied and told them that all of the children display objects are NOT removed when a group is, and then pointed them to the
cleanGroups() function that is currently used in Ricardo Rauber’s popular Director Class—I said that’s what I use in my projects.
To my surprise, another member (FrankS) replied and pointed out that the
cleanGroups() function may not be entirely efficient in all scenarios (and could even lead to memory leaks… ouch!), and generously provided an alternative.
After that, another member (p120ph37) replied and provided their own solution, which is actually a patch for the built-in
display.newGroups() function that will remove all child objects AND groups just by calling
The only catch to p120ph37’s solution is, in order for it to work you must place his
display.newGroups replacement at the very top of your main.lua file, before any groups are created in your app (not really a “catch” though, just an important warning).
Since both are really great solutions, and since the first one (FrankS) actually calls
removeSelf() on objects and groups, then why not combine both for maximum effect? So that’s exactly what I did.
Download the module here: cleangroup.lua
To use it, place cleangroup.lua in your project’s folder and make sure you put the following code at the top of your main.lua file, before any other “require” statements, and especially before any calls to
require( “cleangroup” )
Then, when you want to get rid of a group (and all of its children, child groups, etc.), just call:
cleanGroup( myGroup ) myGroup = nil
And that’s it. This is a perfect example of how simple collaboration and participating in constructive forum threads can help make everyone’s projects better in some way.
Happy memory-leak prevention and code optimization :-)
UPDATE: The script has been updated to version 1.1, which will check a display object for a touch listener and remove it from the object before calling
removeSelf(). The download link above has been updated as well.