removeSelf()一个零值错误

时间:2013-07-05 17:14:03

标签: lua corona

嗨,出于某种原因,电晕给了我这个错误:尝试索引全局'backC'(零值)

local randomBackC = function()
    backC = display.newImage("Cloud"..tostring(math.random(1, 4))..".png")
    backC.x = math.random (30, 450); backC.y = -20
    physics.addBody( backC, { density=2.9, friction=0.5, bounce=0.7, radius=24 } )
end
timer.performWithDelay( 500, randomBackC, 0 )
end
local function cleanup()
   if backC.y >100 then
       backC:removeSelf()
     end
end
Runtime:addEventListener("enterFrame", cleanup)

任何导致这种情况的想法?

1 个答案:

答案 0 :(得分:3)

backC 可能已被删除,原因是运行时:addEventListener(“enterFrame”,清理)

enterFrame 会一遍又一遍地调用cleanup(),因此您必须在删除 backC 后删除 enterFrame ,如果你想创建多个对象,使它只对函数本地化,因为它可能导致引用问题。

喜欢这个

local randomBackC = function()
    local backC = display.newImage("Cloud"..tostring(math.random(1, 4))..".png")
    backC.x = math.random (30, 450); backC.y = -20
    physics.addBody( backC, { density=2.9, friction=0.5, bounce=0.7, radius=24 } )

    local cleanup
    cleanup = function()
       if backC then
           if backC.y >100 then
               backC:removeSelf()
               backC = nil
               Runtime:removeEventListener("enterFrame", cleanup)
           end
       end
    end
    Runtime:addEventListener("enterFrame", cleanup)
end
timer.performWithDelay( 500, randomBackC, 0 )