Sleep Function |
|
This function to do this without busy waiting does not exist in ANSI C, so it does not exist in stock Lua. However, there are extension libraries and calls to external programs that can do this.
local clock = os.clock function sleep(n) -- seconds local t0 = clock() while clock() - t0 <= n do end end -- warning: clock can eventually wrap around for sufficiently large n -- (whose value is platform dependent). Even for n == 1, clock() - t0 -- might become negative on the second that clock wraps.
There is a sleep function in ExtensionProposal. This may call Win32 Sleep or POSIX usleep. Here's a [usleep/sleep C wrapper] example.
The LuaApr binding has an [apr.sleep()] function that works on Windows & UNIX and supports sub-second resolution.
The lalarm library[1] can set an alarm on POSIX.
winapi (Windows only) has a [sleep] function. [github]
If an FFI interface (Alien or c/invoke -- BindingCodeToLua) is available, you can call whichever OS function you have.
function sleep(n) os.execute("sleep " .. tonumber(n)) end
Windows does not have such a built-in command. However, there's a sleep in the Windows Server Resource Kit. There is also sleep in Cygwin and MinGW. Also, there is "timeout" utility available in Windows 7
os.execute("timeout " .. tonumber(n)) -- specific to win7 (and probably higher)
function sleep(n) if n > 0 then os.execute("ping -n " .. tonumber(n+1) .. " localhost > NUL") end end -- version 20100715 - fixed off-by-one second
This is mainly for Windows in the absence of a sleep command. Other variations exist, e.g. "perl -e 'sleep(" .. tonumber(n) .. ")'"
or "php -r sleep(" .. tonumber(n) .. ");"
.
io.stdin:read'*l'
This is not a sleep but may be useful in similar cases. It waits for the user to press the Enter key.
function sleep(n) local vb = "test.vbs" local f = assert(io.open(vb,"w")) f:write("WScript.Sleep(" .. (tonumber(n) * 1000) .. ")\n") f:close() os.execute(vb) end
See [2].
The POSIX sleep() call provides integer second sleeps.
require "posix" posix.sleep(3)
The select() timeout provides a fairly portable sub-second sleep, if you can tolerate the socket library dependency.
require "socket" function sleep(sec) socket.select(nil, nil, sec) end sleep(0.2)
local ffi = require "ffi" ffi.cdef "unsigned int sleep(unsigned int seconds);" ffi.C.sleep(2)