[英]Corona: attempt to index global 'self' (a nil value)
我有一個創建太空飛船的類,我希望它包含一個使飛船撞到特定牆壁時將其自身移走的函數。 但是,運行下面的代碼,我得到以下錯誤:
...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
您可以這樣做, self
不是顯示對象,或者它沒有對顯示對象的引用,因此object:removeSelf()
存在錯誤
local function xenosColl(event)
if (event.phase == "began" and event.other.myName == "bottomWall") then
event.target:removeSelf()
end
end
如果您想使用自我 ,可以這樣做。 因此,自我現在正在引用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
我最近遇到了相同的錯誤消息; 對我來說,這是一個簡單的語法錯誤,而不是
playerInstance:resetTargetPosition()
我曾經用過
playerInstance.resetTargetPosition()
(請注意.
而不是:
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.