Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
5

Limit TextBox input to numbers?

Asked by
PredNova 130
9 years ago

Is there a way I can only allow numbers 0-9 to be put into a GUI TextBox and to then put those numbers into a IntValue instance? I've tried my self, without limiting what can be put in the box (As I don't know how this would be done) and it still does not work.

while true do wait()
    script.Parent.Value = script.Parent.Parent.Text
end

I'm probably going completely wrong here, But I have no idea of how this would be done x3

0
What else will be put into the text box? If it's just number, I can possibly help you (Using string.sub()) to limit only one place value in the TextBox. alphawolvess 1784 — 9y
0
@Alpha, Literally just a maximum of 3 numbers would be great.. PredNova 130 — 9y

1 answer

Log in to vote
4
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
9 years ago

Although creative, that method will just cause an error. Even if you type in a number, it's still a string (yes, "5" is a string), and IntValues error if you try to give them strings.

A common method is to use the tonumber function. This function attempts to convert a string into a number, and then return that number. If the string isn't an actual number, then it just returns nil.

print(tonumber("5")) --> 5
print(tonumber("Hello world!")) --nil

It is usually sufficient to just check when you get the input if it's a number or not;

if tonumber(textBox.Text) then

Although you could just directly not allow any non-number input;

if not tonumber(textBox.Text) then 
    textBox.Text = ""
end


On a side note, don't use while loops like you're doing. It's much better to use events, such as Changed, for efficiency purposes.

0
Thank you! :) PredNova 130 — 9y
Ad

Answer this question