I tried to use string.gsub (String, string.lower ('LocalPlayer'), 'LocalPlayer'), but it only get all localplayer.
I wanted to get all LocalPlayer, how to get it?
Your wording poses confusion. What exactly do you want to do? Are you trying to change every account of “LocalPlayer” to use proper capitalisation or are you attempting to get every instance of LocalPlayer present in the string?
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.
What exactly are you trying to do? What do you mean by “get?”
Edit: Basically what this does is it lowers your string so you can search for a single pattern (“localplayer”) and then replace all of the "localplayer"s with “LocalPlayer”
An alternative to the above is to adjust your search argument to use Lua string patterns targeting upper and lower case letters instead of the word you want to replace. Ie. you’d use “[Rr][Oo][Bb][Ll][Oo][Xx]” instead of Roblox if you were looking to replace the word Roblox.
This doesn’t really work if you need the search word to be dynamic, and I recommend you stick with lowercasing the string instead.
The only downside to this solution is that now the rest of the string has been made lowercase, even if that was not the intention. Another approach that avoids this problem is to pass a function to gsub:
local String = 'LocalPlayer localplayer LoCALPlayeR CAPITAL WORDS'
print((String:gsub("%w+", function(word)
if word:lower() == "localplayer" then
return "LocalPlayer"
end
end)))
Roblox doesn’t mention anything about running a function through gsub in documentation (not even in the wiki before), so this is really good information.
You’ll be surprised to learn, then, that tables are also acceptable substitution arguments. Here’s another valid (yet completely unnecessary) solution using a table with a metatable
local String = 'LocalPlayer localplayer LoCALPlayeR CAPITAL WORDS'
print((String:gsub("%w+", setmetatable({}, {__index = function(t, k)
return k:lower() == "localplayer" and "LocalPlayer" or nil
end}))))