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

Only allow numbers in text box?

Asked by
Oficcer_F 207 Moderation Voter
5 years ago

Hello, I have a text box where you can donate points to your team. And obviously, the game will break if you donate a string to an int value. So, how can I make it possible to only be able to write numbers in the text box?

Please don't take this question down, I have looked everything up, and this is my last resort,

BTW THIS IS NOT A REQUEST, I JUST WANT TO KNOW WHAT STRING MANIPULATION I NEED TO USE AND HOW I USE IT!

Thank you.

2 answers

Log in to vote
4
Answered by
MrMedian 160
5 years ago
Edited 5 years ago

SummerEquinox's answer probably works, but here's a much simpler way

TextBox:GetPropertyChangedSignal("Text"):Connect(function()
    if tonumber(TextBox.Text) then
        -- send the donation
    else
        TextBox.Text = "Enter a number to donate" -- do not send the donation
    end
end)

tonumber is a Lua function that checks if the string can be turned into a number. It is related to tostring if you've heard of that

Note: tonumber returns nil if it can't convert the string to a number, but if it can then it returns the string converted to a number

0
You should also mention to number returns nil if it cannot concert its arguments to a number. Good answer nonetheless User#19524 175 — 5y
0
convert* User#19524 175 — 5y
0
This is definitely the more ideal solution, I kind of jumped on string manipulation since he mentioned it. OP use this instead. SummerEquinox 643 — 5y
0
But what if I dont want to allow negative numbers either?? Oficcer_F 207 — 5y
View all comments (2 more)
0
Should I just use: if newValue < 0 then... Oficcer_F 207 — 5y
0
Well, I think you would want newValue >= 0 but yeah that’s the way to do it MrMedian 160 — 5y
Ad
Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

Say you have a TextBox - you can allow only numbers (where num >0) to be typed in it with the following code:

function Format(t)
    return t:gsub("%D", "")
end

script.Parent:GetPropertyChangedSignal("Text"):Connect(function()
    script.Parent.Text = Format(script.Parent.Text)
end)

If you wanted to check the text afterwards - you could do:

script.Parent.FocusLost:Connect(function()
    if string.match(script.Parent.Text, "%D+") then
        print('Text is not a positive number')
        script.Parent.Text = "TextBox"
    end
end)
0
Respect iuclds 720 — 4y

Answer this question