Hello all...
I've been looking up how to have leading 0s on my score displayed on screen.
Some of the explanations I've seen look very complicated.
How difficult is it to have, say 00050 rather than just 50 displayed as the player score.
Thanks
Peej
Go to the bottom of this comment if you just want the code.
We overcomplicate simple things - the Internet
Jokes aside. Basically, you have to convert the number, or score in this case, to a string.
Next you have to loop I from 1 though how long you want the string to be in characters subtracted by the length of the number in characters.
score = 50 function blah(number,count) local s=tostr(numb) -- local variable 's' has to be a string or else we will run into an error. for i=1,cnt-#s do end end |
In this example, we have the parameters numb and cnt, and the variable, score.
Here's what these function parameters are:
cnt - The length of the string that is returned
numb - the Number that will be converted to a string
In the for loop, we will set the variable 's' to "0" joined with var 's'.
score = 50 function blah(number,count) local s=tostr(numb) -- local variable 's' has to be a string or else we will run into an error. for i=1,cnt-#s do s="0"..s end end |
Lastly, the function should output the string:
score = 50 function blah(number,count) local s=tostr(numb) -- local variable 's' has to be a string or else we will run into an error. for i=1,cnt-#s do s="0"..s end return s end |
Here's the result:
score=50 function str_score(numb,cnt) local s=tostr(numb) for i=1,cnt-#s do s="0"..s end return s end print(str_score(score,5)) |
If you want to make sure the string isn't longed that the max character count, then copy the code below:
score="50" function str_score(numb,cnt) local s=tostr(numb) for i=1,cnt-#s do s="0"..s end return sub(s,-5,-1) end print(str_score(score,5)) |
I hope this helped and the explanation was okay.
Easier way FELICE showed me years ago, @Peej.
-- reverse sub reads from right -- to left, thanks felice function dec(a,b) return sub("0000"..a,-b) end |
Sorry to take so long thanking you both for your help.
I understood evman2k on the first reading, which is great.
dw817 explanation with sub intrigued me.
Using that method, I see I'd have to know how long the string is so it looks like I should combine both explanations, convert the score to a string, see how long the string is and use that as the -x variable at the end.
Cheers both
EDIT: I looked at this again and yep... It now works perfectly. Thanks again.
Glad to help, @Peej. I'm actually working on something very similar to this right now. Will post it when ready.
[Please log in to post a comment]