🎓 A1Learner
🔍
0 of 52 lessons completed

Lua Gsub with Functions

string.gsub replaces matches in a string, and the replacement can be a function or a table instead of a fixed string. With a function, each match is passed to the function, and with a table, each match is looked up in the table.

A function can transform each match

The function receives the matched word and returns its uppercase form.

local new, n = string.gsub("a cat sat", "cat", function(word) return string.upper(word) end)
print(new, n)

A function receives captures separately

With two captures, the function gets two arguments and can swap them.

local new, n = string.gsub("red blue", "(red) (blue)", function(first, second) return second .. " " .. first end)
print(new, n)

A table replaces each match by lookup

The three letter pattern matches every word, but pig has no table entry, so it stays.

local dict = {cat = "dog", sat = "slept"}
local new = string.gsub("cat sat pig", "%a%a%a", dict)
print(new)

Example

local words = "cat sat pig"
local dict = {cat = "dog", sat = "slept", pig = "hog"}
local replaced, n1 = string.gsub(words, "%a%a%a", dict)
print(replaced, n1)
local loud, n2 = string.gsub(words, "%a%a%a", function(w) return string.upper(w) end)
print(loud, n2)

Key points

  • Function replacement: gsub calls the function once per match and uses its return value as the replacement.
  • Function argument: the function receives the whole match, or the captures when the pattern has captures.
  • Table replacement: gsub looks up each match in the table and uses the value found.
  • Missing table key: a match with no table entry is left unchanged.
  • Count: gsub returns the new string and, second, the number of replacements made.

In this example, the table call replaces all three words by lookup, and the count 3 proves three replacements were made. The function call then uppercases the same three words, and its count is also 3.

Note

a function that returns nil or false leaves that match unchanged.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What is the second value returned by string.gsub?