gigapico00
gigapico00

Reputation: 467

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

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?

Upvotes: 3

Views: 555

Answers (1)

Javier Moreno
Javier Moreno

Reputation: 93

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.

Upvotes: 2

Related Questions