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

Checking for Number or String?

Asked by 10 years ago

I am making a script but I want it to check if the 'Value' entered is a number or a string. I am using

if script.Parent.TextBox.Text - 1 ~= nil then

This works great for a number. But when I enter text I get this:

if script.Parent.Insert.Text - 1 == nil then

'attempt to perform arithmetic on field 'Text' (a string value)' I need a more efficient way to detect whether it is a number or a string. Can anyone help?

1 answer

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

If a string can be turned into a number, then tonumber will return that number; if not it will return nil.

local number = tonumber(str);

if number then
    print( number * 5 ); -- We can do math on it since it's a number
else
    -- number is nil
    print("You didn't enter a number")
end

Ad

Answer this question