So basically you can’t remove the scene you’re in because there wouldn’t be anything to show. You can remove the scene once another scene is on screen.
This is why the timer works. Your next scene is showing. You can also put the removeScene() call in the scene:hide() function during the “did” phase since the scene is hidden at that point. You can’t during the “will” phase since the scene is still on screen.
This trips up a lot of people. You have other options too. Set the scenes to auto remove by setting:
composer.recycleOnSceneChange = true
https://docs.coronalabs.com/api/library/composer/recycleOnSceneChange.html
This only dumps the view group, the scene’s module is still required. This means when you go back to the scene, scene:create() will be called again, but any objects that exist outside of there or variables that are set, won’t be reset.
The big question is why are you removing the scene?
-
to save memory?
-
to make it easy to go back to the scene and have everything in place?
-
Some other reason?
Composer caches scenes to be more efficient when returning to them. Unless you’re hitting memory limits, you shouldn’t be removing scenes in general. However most of the time, people want to do this because it makes the scene start fresh. Your scene is a complete Lua module. That means you can define local variables at the top that can hold values like scores, lives, spawned enemies. Removing the scene is an easy, but cruel way to do this. Now Composer has to reconstruct the scene, reading all the image files, audio files, etc. in and doing all that work again, when a few lines of code could reposition objects, purge spawn tables and clear the high score.
Now personally being lazy, I’ll make Composer do the work again to save me coding time. Best practice? Probably not. Since memory is not a concern, I will stack my removeScene/gotoScene like this:
composer.removeScene(“theSceneImGoingTo”)
composer.gotoScene(“theSceneImGoingTo”)
I don’t have to deal with any timing issues and it’s simple. If memory is a concern, then I might do something more like:
-- scene I just went to function scene:show( event ) local phase = event.phase if "did" == phase then local previous = composer.getSceneName("previous") composer.removeScene(previous) end end
But as I mentioned above, we’ve recently discovered and tested, what probably should be the best practice with this:
-- scene you are leaving function scene:hide( event ) local phase = event.phase if "did" == phase then local current = composer.getSceneName("current") composer.removeScene(current) end end
I would recommend going with this method even though it not what I do I can be a bad programmer at times!
Rob