objectmemorymemory-managementluacoronasdk

There is a problem in memory-management of object in lua programming


I'm making a shooting game with solar 2d, everything was working fine but after some time I feel that the games frame rate is dropping, but I did steps to delete my laser when the task finishes

local function fireLaser()
    audio.play( fire sound )

    newLaser = display.newImageRect( mainGroup, objectSheet, 5, 14, 40 )
    physics.addBody( newLaser, "dynamic", { isSensor=true } )
    newLaser.isBullet = true
    newLaser.myName = "laser"

    newLaser.x = ship.x
    newLaser.y = ship.y
    newLaser:toBack()

    transition.to( newLaser, { y=400, time=500,
        onComplete = function()display.remove( newLaser ) end
   } )
end

I think what is happening, that onComplete calls the display.remove( newLaser ) after 600ms but the function again called but in less than 600ms , say 400ms, so display.remove( newLaser ) dump the first object which is called on first clicked and remove the second one or say latest one, but if the player continuously clicking the fire laser button, and each click has a difference of less than 600 ms, then nothing would be removed. Please Help me as soon as possible.


Solution

  • If you are only using newLaser inside of fireLaser you should define it as a local variable.

    This will seem like a insignificant change, but when you do

            onComplete = function() display.remove(newLaser) end
    

    you are creating a enclosed function.

    When a function is written enclosed in another function, it has full access to local variables from the enclosing function; this feature is called lexical scoping. Although that may sound obvious, it is not. Lexical scoping, plus first-class functions, is a powerful concept in a programming language, but few languages support that concept. - Programming in Lua: 6.1 – Closures

    This does not work when newLaser is global because each call to fireLaser is acting on the same global variable of newLaser rather than a unique local variable.