Creating a timer using Lua

Try lalarm, here: http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/

Example (based on src/test.lua):

-- alarm([secs,[func]])
alarm(1, function() print(2) end); print(1)

Output:

1
2

If milisecond accuracy is not needed, you could just go for a coroutine solution, which you resume periodically, like at the end of your main loop, Like this:

require 'socket' -- for having a sleep function ( could also use os.execute(sleep 10))
timer = function (time)
    local init = os.time()
    local diff=os.difftime(os.time(),init)
    while diff<time do
        coroutine.yield(diff)
        diff=os.difftime(os.time(),init)
    end
    print( 'Timer timed out at '..time..' seconds!')
end
co=coroutine.create(timer)
coroutine.resume(co,30) -- timer starts here!
while coroutine.status(co)~="dead" do
    print("time passed",select(2,coroutine.resume(co)))
    print('',coroutine.status(co))
    socket.sleep(5)
end

This uses the sleep function in LuaSocket, you could use any other of the alternatives suggested on the Lua-users Wiki

Tags:

Timer

Lua