在游戏开发的时候,偶尔会遇到需要对按钮点击添加 CD(冷却时间 Cool Down Time) 的需求,那么就需要比较两次点击之间的时间间隔!首先想到的就是使用 Lua 中的系统函数 os.clock()。
os.clock()
返回程序使用的按秒计 CPU 时间的近似值。
那么就可以很愉快的搞定这个需求了:
local test = {}
function test:clickBtn()
local curTime = os.clock()
if test.recordTime and curTime - test.recordTime < 2 then
print("2s cd中")
return
end
-- do something
test.recordTime = curTime
end
本来以为这样就 OK 了,万万没想到,os.clock() 居然偶尔会返回一个负数!所以就直接 GG 了!!!
网上搜了一下发现有不少人也都遇到过这个问题,返回负数的原因是 Lua 的 os.clock() 会调用 C 的 clock 函数,该函数返回值依赖于操作系统,在32为系统中会有溢出风险!
那么怎么解决这个问题呢?很简单,用 socket.gettime() 或者 os.time() 来替换 os.clock() 获取时间即可!
local test = {}
local socket = require("socket")
function test:clickBtn()
local curTime = socket.gettime()
print(curTime)
if test.recordTime and curTime - test.recordTime < 2 then
print("2s cd中")
return
end
-- do something
test.recordTime = curTime
end
对时间精度要求高就用 socket.gettime(),对时间精度要求不高就用 os.time()!