在IT技术中,如何添加延迟/定时器?

3

我目前使用Corona SDK,Lua作为我的主要语言。

我遇到一个问题,当我运行这段代码时,它会自动给我输出我所指定的'light'的值。我设置了light = 2,并且通过这个循环,它应该每次递减1,直到light <= 0。当我运行程序时,值会一次性显示为1、0、-1。我想知道是否可以在每个值之间添加一个延迟。

我正在制作一个“西蒙说”游戏,但由于它同时运行了所有操作,所以方块不会发光。

以下是代码:

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

    while(light >= 0) do
        light = light - 1
        print(light)
    end
end 
1个回答

1
这是 Corona SDK 的一个简单的 timer.performWithDelay 函数。您可以在此处查看更多: https://docs.coronalabs.com/api/library/timer/performWithDelay.html 以下是适合您问题的示例代码。
注意: 我基于您上面提供的代码编写了此代码。
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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接