If milisecond accuracy is not needed, you can simply go for a coroutine solution that you periodically resume, for example, at the end of the main loop. For instance:
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 can use any other alternatives suggested in the Lua-users Wiki
source share