There's no need to reinvent the wheel here, because regular string output formatting in C (and GDScript!) already provides a mechanism for leading zeroes.
When using string formatting, you can use the placeholder %d
to signify an integer number. Formatting/inserting the number 5
with this will result in… 5
. This is not exactly what we want.
If you provide a minimum length, you'll end up with a padded number: Formatting/inserting 5
using %2d
will get you 5
. This is close, but still not perfect.
Finally, we can add a leading zero to signify that we actually want to pad with zeroes rather than spaces: Formatting/inserting 5
using %02d
will get us 05
. This is exactly what we want! And even better, if you pass in 10
you'll get 10
!
The rest works pretty much the way you did:
# Demo variable, 1 hour (3600 seconds), 2 minutes (120 seconds), and 3 seconds
var time = 3723 # 3600 + 120 + 3
var seconds = time % 60
time /= 60
var minutes = time % 60
time /= 60
var hours = time
# Here's all the magic happening
print("%02d:%02d:%02d" % [hours, minutes, seconds])
# Output: 01:02:03