0
我對Lua相當陌生,在我的代碼中一個特定的命令一直在導致我一些主要問題。Lua:timer.cancel - >'試圖索引一個零值'
我一直在試圖取消計時器:
currentPuddleDelay = timer.performWithDelay(puddleDelay, createPuddle);
,我顯示的錯誤是:
Attempt to index a nil value
File: ?
stack traceback:
?: in function 'cancel'
game.lua:534: in function '?'
?: in function 'dispatchEvent'
?: in function '_saveSceneAndHide'
?: in function 'gotoScene'
game.lua:452: in function '?'
?: in function <?:182>
從我已經研究過,可能會出現這個問題時,計時器是在一個函數內,是本地的,但是,我的代碼中的計時器是全局的,所以我不認爲這是問題所在。
下面的代碼問題的位:
local function createPuddle()
local function constantDelay()
local puddle = display.newImage(sceneGroup, "images/puddle.png")
puddle.x = puddleLane
puddle.y = -200
physics.addBody(puddle, "dynamic", {density=0, filter=puddleCollisionFilter})
puddle:applyForce(0, puddleSpeed, puddle.x, puddle.y)
sceneGroup:insert(3,puddle)
local function onPuddleCollision(self, event)
if (event.phase == "began") then
print('puddle collision')
puddle:removeSelf()
puddle = nil
composer.gotoScene("menu")
end
end
puddle.collision = onPuddleCollision
puddle:addEventListener("collision")
end
local constantDelayTimer = timer.performWithDelay(puddleDelay/2,constantDelay,1)
currentPuddleDelayHold = timer.performWithDelay(puddleDelay, createPuddle);
end
currentPuddleDelay = timer.performWithDelay(puddleDelay, createPuddle);
在節目
再後來就:
timer.cancel(currentPuddleDelay)
任何幫助將不勝感激。
你是否檢查過'currentPuddleDelay'的內容?你確定它可以在執行'timer.cancel()'的行上訪問嗎?看看類似的問題:https://stackoverflow.com/questions/32403817/corona-timer-cancel-returns-attempt-to-index-a-nil-value – Electrix
你爲什麼設置'puddle = nil'裏面' onPuddleCollision'?如果兩次調用'onPuddleCollision'的同一個實例並且兩次調用'event.phase ==',那麼這將產生一個「嘗試索引nil值」的錯誤。 –