What is the string.gsub() method in Lua?
Overview
In Lua, the built-in string.gsub string manipulation method is used to substitute a substring with another substring value.
The string.gsub method accepts three string parameters. It will replace the segment of the first parameter (mainString) provided as the second parameter (substring), with the third parameter (replacement). It will return the mainString with the newly added substring upon success.
Syntax
string.gsub(mainString,substring,replacement)
Parameters
mainString: This is a string value that may contain the indicatedsubstring.substring: This is the string value which, when found in themainString, will be replaced.replacement: This is the string value that will be used to replace thesubstringvalue in themainString.
Return value
This method returns a modified form of the mainString with the replacement in it. The count that shows how many times the substring is found is also in it.
If the substring isn’t found in the mainString, the initial form of the mainString value would be returned with a substring occurrence count of 0.
Code example
In the code snippet below, we’ll replace a chunk of some string value with another using the string.gsub() method:
--declare a few variablesmainString = "As you live, live as you live"substring = "live"replacement = "grow"--call substring methodoutput = string.gsub(mainString,substring,replacement)--print the output to screenprint(output)--try string.gsub where substring could not be foundprint(string.gsub("a sg s sg","p","qhj"))--in this case it substring was found.print(string.gsub("as g s sg","sg","hum"))
Code explanation
- Lines 2 to 4: We declare the variables.
- Line 7: We use the
string.gsubmethod. - Line 9: We print the output of the method on the screen.
- Line 12: We call the
string.gsubmethod and try to replace a substring that can’t be found in themainstring. - Line 14: We replace a substring using the
string.gsubmethod.
Output
The count is not returned in the output of operation in line 7 (unlike in lines 12 and 14). This is because the count will be returned on the direct print of the operation (in lines 12 and 14). But it won’t happen if the return is saved in output and then printed. We should simply put the method at the execution time and keep the count, not track it.