我正在尝试编写一个函数,将剩余的秒数转换为人类可读的格式。我遇到的问题(我认为)是我的第二个while循环试图在第一个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 .. ' hours, '
elseif hr == 1 then
hrDisplay = '1 hour, '
end
if min > 1 then
minDisplay = min .. ' minutes and '
elseif min == 1 then
minDisplay = '1 minute and '
else
minDisplay = ''
end
return hrDisplay .. minDisplay .. secs .. ' seconds'
end
答案 0 :(得分:0)
您的代码几乎没有错误,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 .. ' minute, '
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