LUA Sleep Function

本文介绍了在Lua中实现程序暂停功能的各种解决方案,包括使用忙等待、C扩展、外部命令如sleep、利用I/O等待、调用WScript以及使用select()函数等方法。这些方案覆盖了不同场景和平台的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://lua-users.org/wiki/SleepFunction

A common need is to pause (sleep) a program for a certain number of seconds, preferably without busy waiting.

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.

Solution: Busy Wait
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.
Solution: C extension

There is a sleep function in ExtensionProposal. This may call Win32 Sleep or POSIX usleep.

The lalarm library[1] can set an alarm on POSIX.

If an FFI interface (Alien or c/invoke -- BindingCodeToLua) is available, you can call whichever OS function you have.

Solution: sleep command
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.

Solution: ping or other programs
function sleep(n)
  os.execute("ping -n " .. tonumber(n) .. " localhost > NUL")
end

This is mainly for Windows in the absence of a sleep command. Other variations exist, e.g. "perl -e 'sleep(" .. tonumber(n) .. ")'".

Solution: I/O wait
io.stdin:read'*l'

This is not a sleep but may be useful in similar cases. It waits for the use to press the Enter key.

Solution: Using WScript (Windows)
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].

Solution: select()

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)
See Also
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值