Search code examples
luacountdown

Is there a way to make a countdown to a specific date in Lua?


So I am just tinkering with Lua after hearing that it was more versatile than python, so I tried to make a countdown to one year, in the form of DDD:HR:MN:SC. If anyone could give me an example it would be much appreciated!


Solution

  • Following code should exactly do what you want:

    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
    }