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 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.

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 variables
mainString = "As you live, live as you live"
substring = "live"
replacement = "grow"
--call substring method
output = string.gsub(mainString,substring,replacement)
--print the output to screen
print(output)
--try string.gsub where substring could not be found
print(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.gsub method.
  • Line 9: We print the output of the method on the screen.
  • Line 12: We call the string.gsub method and try to replace a substring that can’t be found in the mainstring.
  • Line 14: We replace a substring using the string.gsub method.

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.

Free Resources