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. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.
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 2Limiting 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 1Pattern-Based Replacement
Replace all digits with a fixed string.
local s = "abc 123 def 456"
print(s:gsub("%d+", "NUM")) -- abc NUM def NUM 2Function 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.5Table 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 WORLDEscaping 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")
endReturn 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") endTemplate 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.
Learn Lua with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 40
- Lessons
- 159
Frequently Asked Questions
Is the “string.gsub for Transformations” lesson free?
Yes — any 3 lessons of the Lua Academy learning path, including “string.gsub for Transformations”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
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
- Lua Pattern Syntax
- Captures and string.match
- string.gmatch for Tokenization
- string.gsub for Transformations