Creating a timer using Lua

前端 未结 6 827
粉色の甜心
粉色の甜心 2020-12-31 13:50

I would like to create a timer using Lua, in a way that I could specify a callback function to be triggered after X seconds have passed.

What would be the best way t

6条回答
  •  一整个雨季
    2020-12-31 14:08

    After reading this thread and others I decided to go with Luv lib. Here is my solution:

    uv = require('luv') --luarocks install luv
    
    function set_timeout(timeout, callback)
      local timer = uv.new_timer()
      local function ontimeout()
        uv.timer_stop(timer)
        uv.close(timer)
        callback()
      end
      uv.timer_start(timer, timeout, 0, ontimeout)
      return timer
    end
    
    
    set_timeout(1000, function() print('ok') end) -- time in ms
    
    uv.run() --it will hold at this point until every timer have finished
    

提交回复
热议问题