Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to use gsub in InputBox?

local inputbox = script.Parent.Parent.TextBox

inputbox.Changed:Connect(function()
	inputbox.Text = inputbox.Text:gsub("%D" .. "%P" , "")
end)

I need players to be able to input numbers and . The problem is I can still input one letter, however when I am trying to input 2 or more its deleting. Hope someone can help me

2 answers

✓ Accepted answer

To answer this question, I think it's necessary to explain how string patterns [1] work in Lua. In this case, your code takes a string pattern ("%D" .. "%P", which is effectively the same as "%D%P") and applies it with string.gsub to remove anything which doesn't match it. Let's break it into pieces:

%D: Matches anything which isn't a digit.
%P: Matches anything which isn't a punctuation character. Punctuation characters are !@#;,. [2].

When these two patterns are concatenated into %D%P, the pattern matches any non-digit followed by any non-punctuation character. What you want instead is to match all non-digits and periods as a single character, not followed by each other. The correct way to do this is to define a character class set [3], which contains every character except for digits and period. The string pattern for it is the following: [^0-9.]

Basically, the square brackets [] delimit the character class set, 0-9 means it should match digits, . means it should match a period, and finally ^ means that it should be negated, i.e. it should match everything except for the aforementioned characters.

So, your code would look like this:

local inputbox = script.Parent.Parent.TextBox

inputbox.Changed:Connect(function()
    inputbox.Text = inputbox.Text:gsub("[^0-9.]", "")
end)

Disclaimer: untested.

[1]: Programming in Lua: String Patterns
[2]: Roblox DevHub: Character Classes
[3]: Roblox DevHub: Character Class Sets

1 comment

0

Thanks!

string.gsub does not get anything. It returns a string where whatever you found as the “pattern” (second argument) in the string (first argument) it would replace the pattern with whatever is in the third argument (third argument). It also returns how many patterns it found within the string too.

-- this is not typed by me, credits to @Locard for answer in ROBLOX forum.

1 comment

0

Then how can I make it available to input only numbers and . ?

This discussion is preserved as it was. New answers, comments, and votes are closed.