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

How to use gsub in InputBox?

Asked by 4 years ago
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

Log in to vote
1
Answered by
gskw 1046 Moderation Voter
4 years ago
Edited 4 years ago

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

0
Thanks! Sasha_Syshenko 20 — 4y
Ad
Log in to vote
-1
Answered by
Xapelize 2658 Moderation Voter Community Moderator
4 years ago

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.

0
Then how can I make it available to input only numbers and . ? Sasha_Syshenko 20 — 4y

Answer this question