The string format for our purposes is "%02d:%02d" which might look cryptic, but it's actually pretty basic. Using it, we can specify placeholders that have a certain format and then pass in values to fill those placeholders. We could use os.date() for this, but string.format() will do the job more easily. To make the time display in a typical time format ( MM:SS), we need to format a string. This is easy to accomplish using the modulus operator ( %) - essentially secondsLeft % 60 will give us the number of seconds without the minutes. For the seconds variable, we do need the fractional part because that will be the visual "seconds" in the display. Thus, we use math.floor() to generate a whole number and then we store the value as the minutes variable. This will present us with a fractional value, but we don't need the fractional part for the "minutes" aspect of the display. To compute the minutes, we need to reverse the time calculation that we used to convert the time into seconds, so we simply divide the number of remaining seconds by 60. If we didn't do this, the timer wouldn't count down! Optionally, we could add a conditional test after this line to see if secondsLeft equals 0 and, if so, trigger some event indicating that the clock has reached zero. The first step in this function is critical - subtract 1 from secondsLeft. Let's explore this function in greater detail: Local timeDisplay = string.format( "%02d:%02d", minutes, seconds ) Local minutes = math.floor( secondsLeft / 60 ) Time is tracked in seconds convert it to minutes and seconds That's a good start, but it doesn't actually do anything! Let's fix that by first writing a function which updates the visual time display: local function updateTime( event ) If you run the code above, you'll see a large display of 10:00 on the screen.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |