如果不需要毫秒精度,你可以选择定期恢复的协同解决方案,就像在主循环结束时一样,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
这使用了LuaSocket中的sleep函数,你可以使用Lua-users Wiki上建议的任何其他替代方法
试试lalarm
这里:http:
//www.tecgraf.puc-rio.br/~lhf/ftp/lua/
示例(基于src/test.lua):
-- alarm([secs,[func]])
alarm(1, function() print(2) end); print(1)
Run Code Online (Sandbox Code Playgroud)
输出:
1
2
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
53691 次 |
最近记录: |