WHY THIS CODE DOES NOT WORK ? -- removeEventListener causes runtime error

There are only 2 buttons (squares) and one timer.

The timer is called every second and just add +1 to ‘number’

The bottom button (button2) pauses/resumes the timer.

The top button (button1) is to cancel timer and remove everything. But it does not work and shows error in the simulator.

Runtime error
ERROR: nil key supplied for property lookup.
stack traceback:
        [C]: ?
        [C]: ?
        ?: in function ‘removeEventListener’
        ?: in function ‘removeEventListener’
        …users\panuf\desktop\panuf\corona\teste deff\main.lua:17: in function
<…users\panu


–       CODE HERE:


number=0

function play_game()
    local ispaused=false
    
    local button1 = display.newRect( 0, 0, 100, 100 )    
    local button2 = display.newRect( 0, 200, 100, 100 )

    local function inc_number()
        number=number+1
        print(number)
    end
    
    
    local function button1_click()
        button1:removeEventListener( “tap”, button1_click )
        button2:removeEventListener( “tap”, button2_click )
        timer.cancel(timer1)
        button1:removeSelf()
        button1=nil
        button2:removeSelf()
        button2=nil
        
        return true
    end
    
    local function button2_click()
        if ispaused==false then
            timer.pause(timer1)
            print(“PAUSED”)
            ispaused=true
        else
            timer.resume(timer1)
            print(“RESUMED”)
            ispaused=false
        end

        return true
    end
    
    
    timer1=timer.performWithDelay(1000, inc_number, 0)
    
    button1:addEventListener( “tap”, button1_click )
    button2:addEventListener( “tap”, button2_click )
end

play_game()


–    END OF CODE


The error is this line in function button1_click()

button2:removeEventListener( “tap”, button2_click )

What is wrong? Why the function button1_click can’t remove the button2 listener?
 

Because button1_click doesn’t know what button2_click is. You can 1) forward declare that function so that you can remove it as you have coded or 2) move the button2_click function above the button1_click function.

Because button1_click doesn’t know what button2_click is. You can 1) forward declare that function so that you can remove it as you have coded or 2) move the button2_click function above the button1_click function.