Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a delay/timer [duplicate]

Tags:

lua

coronasdk

I am currently using Corona SDK, Lua as my main language. I am having problem with this code where - when I run it, it automatically gives me the values of 'light' in which I stated to print out. I set light = 2 and with this loop, it is supposed to decrement light by 1 each time, until it is <= 0. When I run the program, the values show up as 1,0,-1 all at once. I was wondering if I can add a delay between each values.

I am making a "Simon says" game, and because of this, the boxes do not light up because it runs everything all at once.

Here is the code:

if(count%20 == count - math.floor(count/20)*20) then
    clicked = 0

    while(light >= 0) do
        light = light - 1
        print(light)
    end
end 
like image 704
Jackrow102 Avatar asked Feb 15 '26 06:02

Jackrow102


1 Answers

Here is a simple timer.performWithDelay function of Corona SDK. You can view more here: https://docs.coronalabs.com/api/library/timer/performWithDelay.html

Below is a sample code to which suits your question.

Note: I based the code to your presented code above.

local lights = 2
local timerName -- ADD A TIMER ID TO YOUR TIMER SO THAT WE CAN CANCEL IT LATER ON

local function myFunction()

    lights =  lights - 1

    if (lights >= 0) then
        --DO SOMETHING WITH THE LIGHTS
        print(lights)
    else

        --TERMINATE THE TIMER
        timer.cancel( timerName )

    end

end

  if(count%20 == count - math.floor(count/20)*20) then

    timerName = timer.performWithDelay( 1000, myFunction, 0 )

  end 
like image 81
JLONG Avatar answered Feb 19 '26 11:02

JLONG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!