简体   繁体   中英

Corona: attempt to index global 'self' (a nil value)

I have a class that creates a space ship and I want it to include a function that makes the ship remove itself if it bumps into a specific wall. However, running the code below, I get the following error:

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

>

What am I missing?

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

You can do it like this, the self is not a display object or it has no reference to a display object so there's an error in object:removeSelf()

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

If you want to use self you can do it like this. So the self is now referring to the 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

I recently encountered the same error message; for me, it was a simple syntactic error, instead of

 playerInstance:resetTargetPosition()

I had used

 playerInstance.resetTargetPosition()

(note the . instead of the : )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM