Easiest way to make lua script wait/pause/sleep/block for a few seconds?

前端 未结 19 1239
礼貌的吻别
礼貌的吻别 2020-12-03 00:41

I cant figure out how to get lua to do any common timing tricks, such as

  • sleep - stop all action on thread

  • pause/wait - don\'t go on to the

相关标签:
19条回答
  • 2020-12-03 01:34

    I would implement a simple function to wrap the host system's sleep function in C.

    0 讨论(0)
  • 2020-12-03 01:37

    You can't do it in pure Lua without eating CPU, but there's a simple, non-portable way:

    os.execute("sleep 1")

    (it will block)

    Obviously, this only works on operating systems for which "sleep 1" is a valid command, for instance Unix, but not Windows.

    0 讨论(0)
  • 2020-12-03 01:37

    for windows you can do this:

    os.execute("CHOICE /n /d:y /c:yn /t:5")
    
    0 讨论(0)
  • 2020-12-03 01:39

    It's also easy to use Alien as a libc/msvcrt wrapper:

    > luarocks install alien
    

    Then from lua:

    require 'alien'
    
    if alien.platform == "windows" then
        -- untested!!
        libc = alien.load("msvcrt.dll")
    else
        libc = alien.default
    end 
    
    usleep = libc.usleep
    usleep:types('int', 'uint')
    
    function sleep(ms)
        while ms > 1000 do
            usleep(1000)
            ms = ms - 1000
        end
        usleep(1000 * ms)
    end
    
    print('hello')
    sleep(500)  -- sleep 500 ms
    print('world')
    

    Caveat lector: I haven't tried this on MSWindows; I don't even know if msvcrt has a usleep()

    0 讨论(0)
  • 2020-12-03 01:40

    For the second request, pause/wait, where you stop processing in Lua and continue to run your application, you need coroutines. You end up with some C code like this following:

    Lthread=lua_newthread(L);
    luaL_loadfile(Lthread, file);
    while ((status=lua_resume(Lthread, 0) == LUA_YIELD) {
      /* do some C code here */
    }
    

    and in Lua, you have the following:

    function try_pause (func, param)
      local rc=func(param)
      while rc == false do
        coroutine.yield()
        rc=func(param)
      end
    end
    
    function is_data_ready (data)
      local rc=true
      -- check if data is ready, update rc to false if not ready
      return rc
    end
    
    try_pause(is_data_ready, data)
    
    0 讨论(0)
  • 2020-12-03 01:40

    This should work:

        os.execute("PAUSE")
    
    0 讨论(0)
提交回复
热议问题