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.
string.gsub(mainString,substring,replacement)
mainString
: This is a string value that may contain the indicated substring
.substring
: This is the string value which, when found in the mainString
, will be replaced.replacement
: This is the string value that will be used to replace the substring
value in the mainString
.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.
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"))
string.gsub
method.string.gsub
method and try to replace a substring that can’t be found in the mainstring
.string.gsub
method.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.