所以我听到Lua比python更多才多艺,所以我试着倒计时一年,以DDD:HR:MN:SC的形式。如果有人能给我举个例子,我会非常感激的!
发布于 2019-11-19 12:21:41
下面的代码应该完全符合您的要求:
local function sleep(s)
local t = os.clock() + s
repeat until os.clock() > t
end
local function getDiff(t)
return os.difftime(t, os.time())
end
local function dispTime(t)
local d = math.floor(t / 86400)
local h = math.floor((t % 86400) / 3600)
local m = math.floor((t % 3600) / 60)
local s = math.floor((t % 60))
return string.format("%d:%02d:%02d:%02d", d, h, m, s)
end
local function countdown(tTbl)
local diff = getDiff(os.time(tTbl))
repeat
print(dispTime(diff))
-- os.execute('echo ' .. dispTime(diff))
sleep(1)
diff = getDiff(os.time(tTbl))
until (diff <= 0)
end
countdown{
day = 24,
month = 12,
year = 2019,
hour = 0,
min = 0,
sec = 0
}发布于 2019-11-19 08:14:29
您可以使用os.date将当前日期提取为一个表,然后只需按如下所示的减法来构建差异:
local function print_remaining(target)
local current = os.date("*t")
print(string.format("%i years, %i months and %i days",
target.year-current.year,
target.month-current.month,
target.day-current.day
))
end
local function countdown(target)
while true do
print_remaining(target)
os.execute('sleep 1')
end
end
countdown {year = 2019, month=12, day=25}如果你想让它更凉爽,当然你必须根据剩下的时间来调整所显示的组件。
受到@csaars回答的启发,我改变了几件事,最后得到了这个结果。
local function split(full, step, ...)
if step then
return math.floor(full % step), split(math.floor(full / step), ...)
else
return full
end
end
local function countdown(target)
local s, m, h, d = split(os.difftime(os.time(target), os.time()), 60, 60, 24)
print(string.format("%i days, %i:%i:%i", d, h, m, s))
if os.execute('sleep 1') then
return countdown(target)
end
end
countdown {year = 2019, month=12, day=25}plit函数比本例所需的要复杂一些,但我认为这是一个很好的机会,可以展示在Lua中使用各种递归函数可以很好地表达一些东西。
发布于 2019-11-25 14:57:30
只要确保倒计时不超过2038年1月19日。Unix时间不能超过这一点。整数溢出是问题所在。
https://stackoverflow.com/questions/58926675
复制相似问题