Codectionary / Developer documentation / Lua

Lua string.gsub replacements

string.gsub replaces pattern matches and returns the new string plus the replacement count. A replacement function receives captures and computes replacement text.

Syntax

local text, count = input:gsub(pattern, replacement)

Examples

Lua string.gsub replacements

Run with standalone Lua 5.4: lua example.lua. These scripts target Lua 5.4 rather than Roblox Luau.

local values = {name = "Ada", role = "editor"}
local text, count = ("Hello $name, $role!"):gsub("%$(%a+)", function(key)
    return values[key] or ("$" .. key)
end)
print(text)
print(count)
  1. Output: Hello Ada, editor! and then 2. The callback resolves captured keys; unknown keys remain visible.

Best practices

  • Use a function when replacement values contain arbitrary percent characters. Strings are immutable; gsub returns a new string.

Runtime & versions

Lua interpreter or a host application. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Lua reference manuals

Specifications & further reading