CORONA: timer.cancel() returns “Attempt to index a nil value”

大兔子大兔子 提交于 2019-12-10 18:13:46

问题


I'm trying to cancel a timer started in a "touch event" function inside another "touch event" function, as shown below:

local function startNewGame(event)
if(event.phase=="ended")then
    local function animationImmaginiOggetti()
      for i=1, 7 do
        transition.to(immaginiOggettiAvvioPartita[i],
                      { time = 200, delay = 0, xScale = 0, yScale = 0, alpha = 0})
      end
    end
    local function removeImmaginiOggetti()
        if immaginiOggettiAvvioPartita[1] then
            for i=1, 11 do
                immaginiOggettiAvvioPartita[i]:removeSelf()
                immaginiOggettiAvvioPartita[i] = nil
            end
        end
    end

    local tmrAIO = timer.performWithDelay(4000, animationImmaginiOggetti, 1)
    local tmrRIO = timer.performWithDelay(4250, removeImmaginiOggetti, 1)
end
end


local function replayGame(event)
    if(event.phase=="ended")then
        timer.cancel(tmrAIO)
        timer.cancel(tmrRIO)
    end
end

startBTN:addEventListener("touch", startNewGame)
replayBTN:addEventListener("touch", replayGame)

My problem is that Corona returns

"File: ? Attempt to index a nil value" on timer.cancel (tmrAIO).

What am I doing wrong?


回答1:


The problem is the following, the variables tmrAIO and tmrRIO are local to the function startNewGame, that means they can only be accessed from the scope defined by startNewGame and right now you are trying to access both from outside that function and they are not defined in that scope that's why the nil value.

Solution:

local tmrAIO
local tmrRIO

local function startNewGame(event)
    if(event.phase=="ended")then
        local function animationImmaginiOggetti()
          for i=1, 7 do
            transition.to(immaginiOggettiAvvioPartita[i],
                          {time = 200, delay = 0, xScale = 0, yScale = 0, alpha = 0})
          end
        end
        local function removeImmaginiOggetti()
            if immaginiOggettiAvvioPartita[1] then
                for i=1, 11 do
                    immaginiOggettiAvvioPartita[i]:removeSelf()
                    immaginiOggettiAvvioPartita[i] = nil
                end
            end
        end

        tmrAIO = timer.performWithDelay(4000, animationImmaginiOggetti, 1)
        tmrRIO = timer.performWithDelay(4250, removeImmaginiOggetti, 1)
    end
end

local function replayGame(event)
    if(event.phase=="ended")then
        timer.cancel(tmrAIO)
        timer.cancel(tmrRIO)
    end
end

startBTN:addEventListener("touch", startNewGame)
replayBTN:addEventListener("touch", replayGame)

As you can see I declared tmrAIO and tmrRIO outside of the scope of startNewGame making them accessible anywhere inside this file.



来源:https://stackoverflow.com/questions/32403817/corona-timer-cancel-returns-attempt-to-index-a-nil-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!