Lua 中有没有一种方法可以倒计时到特定日期?

所以我听说 Lua 比 Python 更加多才多艺,就在研究一下 Lua。我试着做了一个倒计时到一年的形式,即 DDD:HR:MN:SC。如果有人能给我一个例子,那就太感谢了!

点赞
用户9922866
用户9922866

要获取详细的日期信息,请使用带有字符串参数“*t”的函数os.date。这个调用会返回一个包含分钟、日、年等信息的表。

使用这个表,你可以编写一个简单的函数来检索当前日期并按你喜欢的方式格式化它。在这个示例中,我选择了“yyyy/mm/dd”的格式。

function format_date()
    local function tbl = os.date("*t")
    local date = string.format("%d/%d/%d", t.year, t.month, t.day)
    return date
end

print(format_date())

> 2019/11/19

函数os.time返回自当前纪元开始以来的秒数。这可以是生成倒计时器的另一种方式。

这里是一个关于Lua OS库的页面链接。

2019-11-19 05:54:50
用户4984564
用户4984564

你可以使用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}

split函数对于这个示例来说有点过于复杂了,但我认为这是展示Lua中使用可变递归函数表达一些东西有多么好用的好机会。

2019-11-19 08:14:29
用户10126088
用户10126088

以下代码应该完全满足你的需求:

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 12:21:41
用户12430009
用户12430009

请确保倒计时不超过2038年1月19日,否则Unix时间将无法使用。 整数溢出是问题的原因。

Just make sure that the countdown isn't past January 19, 2038. Unix Time won't work past that. Integer Overflow is the problem.
2019-11-25 14:57:30