【发布时间】:2013-08-01 23:54:20
【问题描述】:
我正在尝试通过更改一天中的时间来为游戏制作一个简单的脚本,但我想快速完成。所以这就是我要说的:
function disco ( hour, minute)
setTime ( 1, 0 )
SLEEP
setTime ( 2, 0 )
SLEEP
setTime ( 3, 0 )
end
等等。我该怎么做呢?
【问题讨论】:
我正在尝试通过更改一天中的时间来为游戏制作一个简单的脚本,但我想快速完成。所以这就是我要说的:
function disco ( hour, minute)
setTime ( 1, 0 )
SLEEP
setTime ( 2, 0 )
SLEEP
setTime ( 3, 0 )
end
等等。我该怎么做呢?
【问题讨论】:
Lua 没有提供标准的sleep 函数,但是有几种方法可以实现一种,详见Sleep Function。
对于 Linux,这可能是最简单的一个:
function sleep(n)
os.execute("sleep " .. tonumber(n))
end
在 Windows 中,您可以使用ping:
function sleep(n)
if n > 0 then os.execute("ping -n " .. tonumber(n+1) .. " localhost > NUL") end
end
使用select 的方法值得关注,因为它是获得亚秒级分辨率的唯一可移植方式:
require "socket"
function sleep(sec)
socket.select(nil, nil, sec)
end
sleep(0.2)
【讨论】:
os 是一个标准的Lua 库,我自己在Windows XP 下使用ping 测试了它,它运行良好。你使用的是什么版本的 Lua?
os 库。如果是,请指定哪一个,因为它更有可能提供更好的解决方案。
如果你安装了 luasocket:
local socket = require 'socket'
socket.sleep(0.2)
【讨论】:
这个自制函数的精度低至十分之一秒或更小。
function sleep (a)
local sec = tonumber(os.clock() + a);
while (os.clock() < sec) do
end
end
【讨论】:
wxLua 具有三个睡眠功能:
local wx = require 'wx'
wx.wxSleep(12) -- sleeps for 12 seconds
wx.wxMilliSleep(1200) -- sleeps for 1200 milliseconds
wx.wxMicroSleep(1200) -- sleeps for 1200 microseconds (if the system supports such resolution)
【讨论】:
我需要一些简单的轮询脚本,所以我尝试了Yu Hao's answer 中的os.execute 选项。但至少在我的机器上,我不能再用 Ctrl+C 终止脚本。所以我尝试了一个非常相似的函数,使用io.popen 代替,这个函数确实允许提前终止。
function wait (s)
local timer = io.popen("sleep " .. s)
timer:close()
end
【讨论】:
如果您使用的是基于 MacBook 或 UNIX 的系统,请使用:
function wait(time)
if tonumber(time) ~= nil then
os.execute("Sleep "..tonumber(time))
else
os.execute("Sleep "..tonumber("0.1"))
end
wait()
【讨论】:
我知道这是一个非常古老的问题,但我在做某事时偶然发现了它。这是一些对我有用的代码...
time=os.time()
wait=5
newtime=time+wait
while (time<newtime)
do
time=os.time()
end
我需要随机化,所以我添加了
math.randomseed(os.time())
math.random(); math.random(); math.random()
randwait = math.random(1,30)
time=os.time()
newtime=time+randwait
while (time<newtime)
do
time=os.time()
end
【讨论】:
您应该阅读以下内容: http://lua-users.org/wiki/SleepFunction
有多种解决方案,每一种都有描述,了解这一点很重要。
这是我用的:
function util.Sleep(s)
if type(s) ~= "number" then
error("Unable to wait if parameter 'seconds' isn't a number: " .. type(s))
end
-- http://lua-users.org/wiki/SleepFunction
local ntime = os.clock() + s/10
repeat until os.clock() > ntime
end
【讨论】:
function wait(time)
local duration = os.time() + time
while os.time() < duration do end
end
这可能是向脚本添加等待/睡眠功能的最简单方法之一
【讨论】: