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?
01 | for time = 1 , 100 do |
02 | -- % (modulo) gets the remainder of a division |
03 | -- This gives the number of seconds |
04 | seconds = time % 60 |
05 |
06 | -- If we take away the number of seconds, what we get is exactly divisible |
07 | -- by 60 |
08 | remainingTime = time - seconds |
09 | minutes = remainingTime / 60 |
10 |
11 | -- Format as a string |
12 | x = tostring (minutes) .. tostring (seconds) |
13 | end |
This gives us almost what we want, but sometimes the time "1:5" is returned, rather than "1:05", for example.
01 | --[[ |
02 | Function to pad a string with 0s on the left to reach a minimum length |
03 | text: string -> The text to pad on the left with 0s |
04 | targetLength: integer -> The minimum length of the string we'll return |
05 | return -> Input text, left padded with 0s to a minimum of targetLength. |
06 | --]] |
07 | function zfill(text, targetLength) |
08 | -- Work out the number of digits required |
09 | digitsRequired = targetLength - string.len(text) |
10 | padding = string.rep( "0" , digitsRequired) |
11 | return padding .. text |
12 | end |
That should work to achieve the padding we want.
Combining everything we get:
01 | --[[ |
02 | Function to pad a string with 0s on the left to reach a minimum length |
03 | text: string -> The text to pad on the left with 0s |
04 | targetLength: integer -> The minimum length of the string we'll return |
05 | return -> Input text, left padded with 0s to a minimum of targetLength. |
06 | --]] |
07 | function zfill(text, targetLength) |
08 | -- Work out the number of digits required |
09 | digitsRequired = targetLength - string.len(text) |
10 | padding = string.rep( "0" , digitsRequired) |
11 | return padding .. text |
12 | end |
13 |
14 | for time = 1 , 100 do |
15 | -- % (modulo) gets the remainder of a division |
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?