Hello, I have a text box where you can donate points to your team. And obviously, the game will break if you donate a string to an int value. So, how can I make it possible to only be able to write numbers in the text box?
Please don't take this question down, I have looked everything up, and this is my last resort,
BTW THIS IS NOT A REQUEST, I JUST WANT TO KNOW WHAT STRING MANIPULATION I NEED TO USE AND HOW I USE IT!
Thank you.
SummerEquinox's answer probably works, but here's a much simpler way
1 | TextBox:GetPropertyChangedSignal( "Text" ):Connect( function () |
2 | if tonumber (TextBox.Text) then |
3 | -- send the donation |
4 | else |
5 | TextBox.Text = "Enter a number to donate" -- do not send the donation |
6 | end |
7 | end ) |
tonumber is a Lua function that checks if the string can be turned into a number. It is related to tostring if you've heard of that
Note: tonumber returns nil if it can't convert the string to a number, but if it can then it returns the string converted to a number
Say you have a TextBox - you can allow only numbers (where num >0) to be typed in it with the following code:
1 | function Format(t) |
2 | return t:gsub( "%D" , "" ) |
3 | end |
4 |
5 | script.Parent:GetPropertyChangedSignal( "Text" ):Connect( function () |
6 | script.Parent.Text = Format(script.Parent.Text) |
7 | end ) |
If you wanted to check the text afterwards - you could do:
1 | script.Parent.FocusLost:Connect( function () |
2 | if string.match(script.Parent.Text, "%D+" ) then |
3 | print ( 'Text is not a positive number' ) |
4 | script.Parent.Text = "TextBox" |
5 | end |
6 | end ) |