Corona: 尝试索引全局变量 'self' (一个 nil 值)

我有一个创建太空飞船的类,我想要它包括一个函数,如果它撞到特定的墙壁,让飞船自动删除。但是运行下面的代码时,我得到以下错误:

...xenosShip.lua:16:
attempt to index global 'self' (a nil value)
stack traceback:
[C]:?
...xenosShip.lua:16: in function ...xenosShip.lua:14> ?:in function <?:218

我漏掉了什么?

local xenosShip = {}

-- XENOS SHIP COLLISION
local function xenosColl(event)
    if (event.phase == "began" and event.other.myName == "bottomWall") then
    self:removeSelf()
    end
end

-- XENOS SHIP
function xenosShip.new()

    local newXenosShip=display.newSprite( alShipSheet, alShipSeqData )
    newXenosShip:play()
    newXenosShip.x=300
    newXenosShip.y=70
    newXenosShip.myName = "newXenosShip"
    physics.addBody(newXenosShip,"dynamic", {density = 1.0, friction = 0.3, bounce = 1})
    newXenosShip:applyForce(50,2500,newXenosShip.x,newXenosShip.y)
    newXenosShip:addEventListener("collision", xenosColl)

end

return xenosShip
点赞
用户1605727
用户1605727

你可以像这样做,self 不是一个显示对象或者它没有给显示对象引用,所以在 object:removeSelf() 发生了错误。

local function xenosColl(event)
    if (event.phase == "began" and event.other.myName == "bottomWall") then
        event.target:removeSelf()
    end
end

如果你想使用 self,你可以这样做。现在,self 指向 newXenosShip

function xenosShip.new()

    local newXenosShip=display.newSprite( alShipSheet, alShipSeqData )
    newXenosShip:play()
    newXenosShip.x=300
    newXenosShip.y=70
    newXenosShip.myName = "newXenosShip"
    physics.addBody(newXenosShip,"dynamic", {density = 1.0, friction = 0.3, bounce = 1})
    newXenosShip:applyForce(50,2500,newXenosShip.x,newXenosShip.y)
    newXenosShip.collision = function(self,event)
        if (event.phase == "began" and event.other.myName == "bottomWall") then
                self:removeSelf()
        end
    end

    newXenosShip:addEventListener("collision")
end
2013-07-09 16:41:33
用户610979
用户610979

我最近遇到了同样的错误信息;对我而言,它只是一个简单的语法错误,而不是:

 playerInstance:resetTargetPosition()

我使用了

 playerInstance.resetTargetPosition()

(请注意,与 : 相比,使用了 .

2014-05-07 21:02:55