The method gsub is a function which will return the same string after replacing all the "rules" in the pattern string with the replacement string.
For example, let's say you want to get only the numbers from a string, you could do
local str = "I, don't, like, punctuation!!!!!!"
local newString = string.gsub(str, "%p", "")
print(newString)
Essentially, the example above replaced any punctuation (defined by the string pattern %p) and replaced it with an empty string, thereby removing it.
However, gsub will return 2 things: the new string and the no. substitutions.
This can be useful for counting, for example:
local str = "I, don't, like, punctuation!!!!!!"
local _, subs = string.gsub(str, "%p", "")
print(subs)
If the replacement is a function, not a string, the arguments passed to the function are any captures that are made. If the function returns a string, the value returned is substituted back into the string.
[SOURCE]
Example:
string.gsub("I, don't, like, punctuation!!!!!!", "%w+", print)
Example 2
This example will replace with lengths of each word
local str = "I dont like punctuation!"
local newString, _ = string.gsub(str, "(%w+)", function(w)
return string.len(w)
end)
print(newString)
Obviously you can use this for many other rules/string patterns. I mostly use it for either counting or string manipulation within a textbox, i.e. if I want the textBox to only allow numbers as a form of input.
It's actually very useful, this is a great question!
I hope this has cleared it up for you, feel free to mess around a bit, see what you can discover on your own as this is one of those things that takes practice to understand better.
Also, if you're looking for documentation on this, you can check out LUA's official website:
https://www.lua.org/pil/20.1.html
https://www.lua.org/pil/20.2.html
If I answered your question, please make sure to accept my answer :)
1 comment
Great job with your answer, I had a go myself too :)