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

How do I make a TextBox only accept numbers?

Asked by 8 years ago

So I'm making a Light Placing plugin (I know, super original!) and when i click, I want a gui to appear asking you things like "How bright?". But, obviously, is someone typed letters in it, it would obviously error.

0
Have the script check if tonumber(string) ~= nil. tonumber will return nil if the string given is not a number at all. M39a9am3R 3210 — 8y

1 answer

Log in to vote
2
Answered by
theCJarmy7 1293 Moderation Voter
8 years ago

M39a9am3R is right.

--tonumber will turn a string into a number or return nil if the string is not a number
tonumber("hello!")--nil
tonumber("1244")-1244

Then to have the TextBox only use numbers, just do something like this.

textbox = script.Parent.TextBox --or something
textbox.FocusLost:connect(function()
    if tonumber(textbox.Text) then
        --do stuff with textbox.Text being a number
    end
end)

And if you wanted the players not be able to type letters, then do this.

textbox = script.Parent.TextBox --or something
textbox.Changed:connect(function(prop)
    if prop == "Text" then
        if not tonumber(textbox.Text) then
            textbox.Text = textbox.Text:sub(1,#textbox.Text-1)
            --using sub to delete the last thing in the string
            --since this fires every single time they type something, it should delete letters instantly
        end
    end
end)
Ad

Answer this question