lua 编程中对象的内存管理存在问题

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

我正在用 solar 2d 制作射击游戏,一切正常,但过了一段时间我觉得游戏帧率下降了,但我在任务完成后采取了删除激光的步骤

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

我认为发生了什么,onComplete 在 600 毫秒后调用了 display.remove( newLaser ) 但该函数再次调用但不到 600 毫秒,比如 400 毫秒,所以 display.remove( newLaser ) 转储第一个对象这是在第一次点击时调用并删除第二个或说最新的一个,但如果玩家连续点击发射激光按钮,并且每次点击的差异小于 600 毫秒,则不会删除任何内容。 请尽快帮助我。

如果您只在 fireLaser 内部使用 newLaser,您应该将其定义为 local 变量。

这似乎是一个微不足道的变化,但当你这样做时

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

您正在创建一个封闭函数。

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

这在 newLaserglobal 时不起作用,因为对 fireLaser 的每次调用都作用于 newLaser 的同一个 global 变量,而不是一个唯一 local 变量。