Does this code leak?

local function onTap( event ) event.target:removeSelf() end local function spawn() local obj = display.newImage( "apple.png" ) obj:addEventListener( "tap", onTap ) end local function main() spawn() end

When the object is tapped, it will remove itself without any leaks correct? Because there isn’t any reference left pointing to the object.

Just want to make sure I am understanding this correctly.

Without running it and dumping the memory information to the console, it’s impossible to tell.

But, as it is a small piece of code (I’m a firm believer that no code over 8 lines works first time) I think your code will not leak.

  • You’ve used local variables in each function

  • You don’t store objects in any global space

  • The one global space you do use (the display stage) will nil the object reference when calling removeSelf() and you haven’t stored the reference anywhere else

  • You’re not creating closures which will stay around with internal references to objects which have been removed

In fact, I think you could safely add a timer to the main function to continue creating apples and you will not run out of memory - as long as the player keeps destroying the apples or you stop producing them (limit the timer.)

Without running it and dumping the memory information to the console, it’s impossible to tell.

But, as it is a small piece of code (I’m a firm believer that no code over 8 lines works first time) I think your code will not leak.

  • You’ve used local variables in each function

  • You don’t store objects in any global space

  • The one global space you do use (the display stage) will nil the object reference when calling removeSelf() and you haven’t stored the reference anywhere else

  • You’re not creating closures which will stay around with internal references to objects which have been removed

In fact, I think you could safely add a timer to the main function to continue creating apples and you will not run out of memory - as long as the player keeps destroying the apples or you stop producing them (limit the timer.)