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
10 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.

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

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 — 10y
0
@Alpha, Literally just a maximum of 3 numbers would be great.. PredNova 130 — 10y

1 answer

Log in to vote
4
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
10 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.

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

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

1if tonumber(textBox.Text) then

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

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


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 — 10y
Ad

Answer this question