hello i have this function where it tries to separate the time and put it into minutes and seconds, but the only problem is if i try to do any number that is less than 100 because it breaks because tonumber returns nil
local function convertTime(Time)
local minutes = tonumber(string.sub(Time, 1,-3))
local seconds = tonumber(string.sub(Time, -2))
print(minutes,seconds)
local TimeDisplay = string.format("%.2u:%.2u",minutes,seconds)
return TimeDisplay
end
local Time = convertTime(1234)
print(Time) -- output 12:34
error invalid argument #2 to ‘format’ (number expected, got nil)
You could check that minutes exists in your string format. Something like: local TimeDisplay = string.format("%.2u:%.2u",minutes and minutes or 0,seconds and seconds or 0)
Effectively, “minutes and minutes or 0” is saying:
if minutes ~= nil then
return minutes
else
return 0
When you say 12, are you trying to convert 12 to 12:00 or 00:12?
I would assume 00:12 since 0012 = 12 so you can just do tonumber(hours) or 0
local function toTime(time)
local str = tostring(time)
local minutes = str:sub(str:len() - 1)
local hours = str:sub(1, str:len() - 2)
return string.format('%.2u:%.2u', tonumber(hours) or 0, minutes)
end
print(toTime(12))
Oh, then you could just change the variable names (also just an fyi switched the order of seconds/hours to go from biggest to smallest which is generally what people prefer, this will work as normal)
local function toTime(time)
local str = tostring(time)
local minutes = str:sub(1, str:len() - 2)
local seconds = str:sub(str:len() - 1)
return string.format('%.2u:%.2u', tonumber(minutes) or 0, seconds)
end
print(toTime(12))