Composer - memory leak when restarting a scene

I have a very simple setup with just three scenes  - menu, gameplay and holder. As a newbie I am just trying to learn the ropes and ran into a problem. A memory leak has sprung up even though there is nothing more than one image in  each of the scenes.

Right now the setup consists of main.lua leading to menu where one buttonpush leads to gameplay. Now To restart the gameplay level, I just have a button. It leads to a holding level where a timer takes me back to gameplay.

holder code:

function scene:show( event ) local sceneGroup = self.view local phase = event.phase if phase == "will" then local w = display.actualContentWidth local h = display.actualContentHeight local centerX = display.contentCenterX local centerY = display.contentCenterY local bg = display.newRect(centerX,centerY, w, h) bg:setFillColor(153,205,253) sceneGroup:insert(bg) elseif phase == "did" then mytimer = timer.performWithDelay(1000, function() composer.removeScene( "gameplay", false ) composer.gotoScene( "gameplay", { time = 250, effect = "crossFade", params = params } ) end) end end

I have read on the forums that it is very important to cancel all timers and so I do that after the scene is off-screen.

function scene:hide( event ) local sceneGroup = self.view local phase = event.phase if event.phase == "will" then if mytimer~=nil then timer.cancel(mytimer) end mytimer = nil elseif phase == "did" then end end end

Inspite of this very basis code, memory leak is happening. A few kbs at first but as I keep restarting the gameplay level, the memory is creeping up. So what am I doing wrong?

Hi @dimention5studio,

Did you forward-declare (upvalue) the “mytimer” variable? I see that you set it (as a timer) in the “show()” function, but I’m not sure that you actually upvalue declared it outside of any scene handling functions. If you didn’t, then Lua won’t know what you’re referring to, and it won’t know how to cancel the timer in the “hide()” function (thus the timer will never be cancelled, and that could be why you’re getting a leak).

Best regards,

Brent

Hi @dimention5studio,

Did you forward-declare (upvalue) the “mytimer” variable? I see that you set it (as a timer) in the “show()” function, but I’m not sure that you actually upvalue declared it outside of any scene handling functions. If you didn’t, then Lua won’t know what you’re referring to, and it won’t know how to cancel the timer in the “hide()” function (thus the timer will never be cancelled, and that could be why you’re getting a leak).

Best regards,

Brent