0Pricing
Lua Academy · Lesson

string.gsub for Transformations

Replace patterns with strings, functions, or table lookups via gsub.

string.gsub for Transformations is a free Lua Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is string.gsub?

string.gsub(s, pattern, repl, n) replaces occurrences of pattern in s with repl. Returns the new string and the number of substitutions.

Simple String Replacement

Replace all occurrences of a literal substring.

local s = "hello world world"
local result, count = s:gsub("world", "Lua")
print(result, count)  -- hello Lua Lua  2

Limiting Replacements

Pass a fourth argument to limit the number of replacements.

local s = "aaa bbb aaa"
print(s:gsub("aaa", "xxx", 1))  -- xxx bbb aaa  1

Pattern-Based Replacement

Replace all digits with a fixed string.

local s = "abc 123 def 456"
print(s:gsub("%d+", "NUM"))  -- abc NUM def NUM  2

Function Replacement

When repl is a function, it is called with each capture (or whole match) and its return value replaces the match.

local s = "price: 100, tax: 15"
local result = s:gsub("%d+", function(n)
  return tostring(tonumber(n) * 1.1)
end)
print(result)  -- price: 110.0, tax: 16.5

Table Replacement

When repl is a table, each match (or capture) is used as a key; the table value replaces the match.

local vars = {name="Alice", lang="Lua"}
local tmpl = "Hello, {name}! Welcome to {lang}."
local result = tmpl:gsub("{(%w+)}", vars)
print(result)  -- Hello, Alice! Welcome to Lua.

Trimming Whitespace

Use gsub to remove leading and trailing whitespace from a string.

local function trim(s)
  return s:gsub("^%s+", ""):gsub("%s+$", "")
end
print("[" .. trim("  hello  ") .. "]")  -- [hello]

Converting Case

Use gsub with a function to convert each letter to uppercase or lowercase.

local function toUpper(s)
  return s:gsub("%a", string.upper)
end
print(toUpper("hello world"))  -- HELLO WORLD

Escaping Special Characters

Escape all pattern magic characters in a string so it can be used as a literal pattern.

local function escapePat(s)
  return s:gsub("[%(%)%.%%%+%-%*%?%[%^%$]", "%%%1")
end

Return Count Usage

The second return value (substitution count) is useful for detecting whether any replacements occurred.

local s = "no numbers here"
local result, n = s:gsub("%d+", "X")
if n == 0 then print("nothing replaced") end

Template Engine Pattern

A simple template engine replaces {{key}} placeholders with values from a data table.

local function render(tmpl, data)
  return (tmpl:gsub("{{(%w+)}}", data))
end
print(render("Hi {{name}}!", {name="Bob"}))  -- Hi Bob!

gsub Question

When repl in gsub is a function, what is passed to it?

Recap: string.gsub

string.gsub is the Swiss Army knife of string transformation: replace with strings, functions (for dynamic computation), or tables (for dictionary lookups). It also returns the substitution count.

Frequently asked questions

Is the “string.gsub for Transformations” lesson free?

Yes — the full text of “string.gsub for Transformations” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

What will I learn in “string.gsub for Transformations”?

Replace patterns with strings, functions, or table lookups via gsub. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “string.gsub for Transformations” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Lua Pattern Syntax
  2. Captures and string.match
  3. string.gmatch for Tokenization
  4. string.gsub for Transformations
← Back to Lua Academy