So I have a script that when text is typed into the textbox, it filters it to ensure only numbers are typed in:
local textBox = script.Parent
function PositiveIntegerMask(text)
return text:gsub("%D+", "")
end
textBox:GetPropertyChangedSignal("Text"):Connect(function()
-- Replace the text with the formatted text:
textBox.Text = PositiveIntegerMask(textBox.Text)
end)
However, I want to expand this so that it also allows for the “-” character to be typed in to allow for negative numbers. I have tried the following:
"[%D+^%-]"
"^%-%D+"
but neither seem to work, as they either still only allow for numbers only or allow all characters to be typed in. Is there any way for me to do this without going and doing something such as blacklisting every letter and special character on the keyboard except for “-”?
You can simply use the tonumber() function in lua like this
local StringFromTextBox = TextBox.Text
if tonumber(StringFromTextBox) then
--do stuff
end
the tonumber() function checks if a string can be converted to a positive or negative number. If it contains any non-number characters it will return nil
for example:
print(tonumber("-10")) -- Would print -10
print(tonumber("-10s")) -- would print nil
The following pattern allows you to include an optional - symbol at the start of the text. The ? operator allows you to accept 0 or 1 of the given symbol.
You could also use match to do this instead.
local pattern = "%-?%d*"
local internalChange = false
textBox:GetPropertyChangedSignal("Text"):Connect(function ()
if internalChange then return end
internalChange = true
textBox.Text = textBox.Text:match(pattern) or ""
internalChange = false
end)
That sort of worked but since I did not want it clearing when a letter was put in I did the following, while also changing the pattern a bit to match my needs.
local textBox = script.Parent
function PositiveIntegerMask(text)
return text:gsub("[^%-%d]", "")
end
textBox:GetPropertyChangedSignal("Text"):Connect(function()
-- Replace the text with the formatted text:
textBox.Text = PositiveIntegerMask(textBox.Text)
end)