在第一次循环完成后再开始第二次循环

我试图编写一个函数,将剩余的秒数转换为人类可读的格式。我遇到的问题(我认为)是我的第二个 while 循环在第一个完成之前就试图完成它的工作。我最终会得到"1 小时,271 分钟和 37 秒。在我最新的尝试中,我尝试使用 minNeeded,但它也不起作用,因为它在第一次循环完成之前就检查它的存在。我该如何处理这个问题?

function prettyTime(secs)

    local hr = 0
    local hrDisplay = ''
    local min = 0
    local minDislplay = ''
    local minNeeded = 0

    if(secs >= 3600) then
        while secs >= 3600 do
            secs = secs - 3600
            hr = hr + 1
            if secs < 3600 then
                secsRemaining = secs
                minNeeded = 1
            end
        end
    else
        minNeeded = 1
    end
    while true do
        if(minNeeded == 1){
            while secsRemaining >= 60 do
                secsRemaining = secsRemaining - 60
                min = min + 1
            end
        end
    end

    if hr > 1 then
        hrDisplay = hr .. ' 小时,'
    elseif hr == 1 then
        hrDisplay = '1 小时,'
    end
    if min > 1 then
        minDisplay = min .. ' 分钟和 '
    elseif min == 1 then
        minDisplay = '1 分钟和 '
    else
        minDisplay = ''
    end

    return hrDisplay .. minDisplay .. secs .. ' 秒'

end
点赞
用户5525442
用户5525442

你的代码有些 bug, if(minNeeded == 1){ 是语法错误, while true do 将永远不会退出。

以下是简单的转换器,

function prettyTime(sec)
  local sec = tonumber(sec)
  if sec <= 0 then
    return "00.00.00";
  else
    h = tonumber(string.format("%02.f", math.floor(sec/3600)))
    m = tonumber(string.format("%02.f", math.floor(sec/60 - (h*60))))
    s = tonumber(string.format("%02.f", math.floor(sec - h*3600 - m*60)))
    -- return h.."."..m.."."..s
  end

    local res = ''
    if h == 1 then
        res = res ..h .. ' hour, '
    elseif h > 1 then
        res = res ..h .. ' hours, '
    end

    if m <= 1 then
        res = res ..m .. ' minute, '
    elseif m > 1 then
        res = res ..m .. ' minutes, '
    end

    if s <= 1 then
        res = res ..s .. ' second, '
    elseif s > 1 then
        res = res ..s .. ' seconds '
    end
  return res
end

print(prettyTime(3670)) -- 1 hour, 1 minute, 10 seconds
2018-10-08 18:33:03