修正格式以包含前导零,必要时加上

我正在制作一个倒计时计时器。输出在时/分/秒少于10时不显示前导零。

我认为我需要以某种方式使用string.format,但我是新手lua,不太确定如何。

function GetTimeLeft()

local dif = os.time(RELEASEDATE) - os.time()
local timeleft = {
    [1] = math.floor(dif/60/60/24), --day
    [2] = math.floor(dif/60/60)%24, --hour
    [3] = math.floor(dif/60)%60,    --minute
    [4] = math.floor(dif)%60        --second
}

local text = {}
for i=1, #timeleft do
    if i == 1 then
        if timeleft[i] > 0 then
            table.insert(text,timeleft[i])
        end
    else
        table.insert(text,timeleft[i])
    end
end

if dif <= 0 then
    text = RELEASETEXT
else
    text = table.concat(text,":")
end

return tostring(text)

end

期望的是 8:02:08:05 实际的是 8:2:8:5

点赞