TextBox detects integer

How would I make an if statement to make sure the text is equal to a number? For example, if a player wanted to set their walkspeed via textbox, and they for some reason enter a string, it will only detect if it is a number.

1 Like
number = tonumber(TextBox.Text)
if number then
-- Text only includes numbers
end

The lua global tonumber converts the string to a number assuming that no letters or spaces are present.

If a letter or space is present, tonumber returns nil.

You can also convert a number to a string using tostring() or something as simple as ""..123

Here is the explanation behind this. You would first get the Text value. And then use the if tonumber() function to check if it is a number or not.
The tonumber() function will return nil (equivalent to not true AKA false) if the string cannot be directly equated to a numerical value.

The use method would be

 local text= TextBox.Text
 if tonumber(text) then 
 print(“this is a number”)
 end

Wow, is it really that simple? Sorry for wasting your time if I did…

Don’t be. It’s entirely alright. I also left as detailed an explanation as possible so you will actually be able to remember this piece of info the next time you need it. Good luck with your scripting :slight_smile:

I recommend using code blocks so that the code pops from the background and is easier to read, code blocks are generated when using ``` in front of and at the end of your code.

Example:

print("Hello World")

image

returns nil, method is correct either way though