How would I personal check if a Textbox is contained with mathematical characters such as a number? If there isn't a way that would be fine, I'm asking such a question because I Technically don't know how to do it, and would help making a Passcode.
How to tell if a Text is made up of numbers?
2 answers
tonumber is a function that converts a string into a number. It returns nil if the string does not exactly represent a number:
print( tonumber("12345") ) -- 12345
print( tonumber("12345d") ) -- nil
print( tonumber("d12345") ) -- nil
print( tonumber("123d45") ) -- nil
print(tonumber("1.2")) -- 1.2
print(tonumber("5.")) -- 5
It's pretty easy to tell if a string is a number:
if tonumber(text) ~= nil then
-- or equivalently
if tonumber(text) then
If may not be what you want, because it accepts things like hex and exponential notation (I think there's also a binary, and who knows what else):
print(tonumber("1.2e3")) -- 1200
print(tonumber("0x15")) -- 21
In that case, it's probably best to use a string pattern.
Patterns are strings which describe more general strings. For instance, "%d" describes any single digit. + means one-or-more of the previous character, so %d+ means one-or-more digits.
Note that this won't accept, e.g., 5.3 since . is not a digit.
If we want to match the whole string, we can do something like this:
if text:match("%d+") == text then
since match will return a piece of text that matches; we just have to ensure it's the whole thing.
Or, you can use the anchor patterns. ^ indicates the beginning of a string and $ the end.
if text:match("^%d+$") then
Yes, there is a way to see if a TextBox contains numbers instead of letters.
This would be done by seeing what tonumber() would return. If letters are the parameter of tonumber(), then it will return nil instead of numbers.
Bellow is an example of what I mean:
if tonumber(VariableHoldingNumbersOrText) ~= nil then
--Coding
end
Now, you probably don't want something like above, so you would use the UserInputService to make a check after the player is finished typing. If you would need an example for this, just comment and I'll make one but I'm pretty sure you are already capable.
This discussion is preserved as it was. New answers, comments, and votes are closed.
