I have a basic for loop
timer, only I'd like to present it to my String in the format of a digital clock I.e '0:00', how would I create the algorithm to Configure it to represent that way?
for time = 1, 100 do -- % (modulo) gets the remainder of a division -- This gives the number of seconds seconds = time % 60 -- If we take away the number of seconds, what we get is exactly divisible -- by 60 remainingTime = time - seconds minutes = remainingTime / 60 -- Format as a string x = tostring(minutes) .. tostring(seconds) end
This gives us almost what we want, but sometimes the time "1:5" is returned, rather than "1:05", for example.
--[[ Function to pad a string with 0s on the left to reach a minimum length text: string -> The text to pad on the left with 0s targetLength: integer -> The minimum length of the string we'll return return -> Input text, left padded with 0s to a minimum of targetLength. --]] function zfill(text, targetLength) -- Work out the number of digits required digitsRequired = targetLength - string.len(text) padding = string.rep("0", digitsRequired) return padding .. text end
That should work to achieve the padding we want.
Combining everything we get:
--[[ Function to pad a string with 0s on the left to reach a minimum length text: string -> The text to pad on the left with 0s targetLength: integer -> The minimum length of the string we'll return return -> Input text, left padded with 0s to a minimum of targetLength. --]] function zfill(text, targetLength) -- Work out the number of digits required digitsRequired = targetLength - string.len(text) padding = string.rep("0", digitsRequired) return padding .. text end for time = 1, 100 do -- % (modulo) gets the remainder of a division -- This gives the number of seconds seconds = time % 60 -- If we take away the number of seconds, what we get is exactly divisible -- by 60 remainingTime = time - seconds minutes = remainingTime / 60 -- Format as a string minuteText = tostring(minutes) secondText = zfill(tostring(seconds), 2) print(minuteText .. ":" .. secondText) end
Closed as Not Constructive by User#24403, DinozCreates, fredfishy, Azmidium, Leamir, and yHasteeD
This question has been closed because it is not constructive to others or the asker. Most commonly, questions that are requests with no attempt from the asker to solve their problem will fall into this category.
Why was this question closed?