Corona:尝试索引全球'自我'(零值)

时间:2013-07-09 15:47:02

标签: function lua corona

我有一个创建太空飞船的类,我希望它包含一个功能,如果它碰到特定的墙壁,它会使船自行移除。 但是,运行下面的代码,我收到以下错误:

...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

&GT;

我错过了什么?

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

2 个答案:

答案 0 :(得分:1)

您可以这样做,self不是显示对象,或者没有对显示对象的引用,因此object:removeSelf()

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

如果你想使用 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

答案 1 :(得分:0)

我最近遇到了同样的错误消息;对我来说,这是一个简单的语法错误,而不是

 playerInstance:resetTargetPosition()

我用过

 playerInstance.resetTargetPosition()

(请注意.而不是: