loopsbuttonluacoronasdk

How to start a looping function with a tap, and stop it with the next tap on the same button in Corona?


I want to create a button that starts a looped function (lets say a ship that fires lasers continuously) with a tap, and then stops with another tap on the button. I'm fairly new to Lua so sorry if this is tribial or something.

I've tried everything, and I know I'm supposed to use touch for this kind of thing, but I just want it to turn the loop on and off. I've somewat achieved this with a code I found in here https://forums.coronalabs.com/topic/2018-touch-tap-event-endless-loop-bug/ but the memory runs out because it keeps sending warnings every milisecond that the timer is already paused or resumed:

WARNING: timer.resume( timerId ) ignored because timerId was not paused

WARNING: timer.pause( timerId ) ignored because timerId is already paused.

--button

local fire = display.newRect( 0, 0, display.contentWidth,    display.contentHeight )
fire:setFillColor( 128, 64, 64 )

--state off

function stateoff()

    timer.pause( timer1 )
    fire:removeEventListener( "tap", stateoff )
    fire:addEventListener( "tap", stateon )
    return true
end

--state on

function stateon()

    function()
    print("fire somthing")
    timer.resume( timer1 )
    fire:removeEventListener( "tap", stateon )
    fire:addEventListener( "tap", stateoff )

end

--loop
timer1 = timer.performWithDelay(1000,stateon,0)

-- start
fire:addEventListener( "tap", stateon )

I just want an on/off button that calls a looped function, or a way to trash the messages,


Solution

  • I would do something more like:

    local fireTimer = nil
    
    local function fireLaser()
         -- your code to create the laser beam and
         -- set it in motion.
    end
    
    local function toggleLaserFire( event )
        if fireTimer then
            timer.cancel( fireTimer )
            fireTimer = nil
        else
            fireTimer = timer.performWithDelay( 1000, fireLaser, 0 )
            fireLaser() -- you probably don't want to wait a second before it fires
                        -- so go ahead and fire one off.
        end
     end
    
     fire:addEventListener( "tap", toggleLaserFire )
    

    I've not tried that code, so there might be typos.