string.gsub() for Substitution
Part of the Logic & Flow section of Coddy's Lua journey — lesson 35 of 54.
When working with strings, you often need to find and replace text. Lua's string.gsub() function makes this easy by performing global substitution—finding all occurrences of a pattern and replacing them with something else.
The basic syntax takes three arguments: the original string, the pattern to find, and the replacement text:
local result = string.gsub(originalString, pattern, replacement)Here's a simple example that replaces all spaces with underscores:
local text = "hello world from lua"
local cleaned = string.gsub(text, " ", "_")
print(cleaned) -- Output: hello_world_from_luaThe function returns two values: the modified string and the number of replacements made. You can capture both if needed:
local result, count = string.gsub("foo bar foo", "foo", "baz")
print(result) -- Output: baz bar baz
print(count) -- Output: 2Unlike some string functions that only find the first match, string.gsub() replaces every occurrence by default, making it perfect for text-cleaning tasks like removing unwanted characters or standardizing formatting.
Challenge
EasyWrite a function cleanText that takes text and returns a cleaned version with all spaces replaced by underscores.
Use string.gsub() to replace every space character in the text with an underscore character.
Parameters:
text(string): The text to clean
Returns: The text with all spaces replaced by underscores (string)
Cheat sheet
The string.gsub() function performs global substitution by finding all occurrences of a pattern and replacing them:
local result = string.gsub(originalString, pattern, replacement)Example replacing spaces with underscores:
local text = "hello world from lua"
local cleaned = string.gsub(text, " ", "_")
print(cleaned) -- Output: hello_world_from_luaThe function returns two values: the modified string and the number of replacements made:
local result, count = string.gsub("foo bar foo", "foo", "baz")
print(result) -- Output: baz bar baz
print(count) -- Output: 2string.gsub() replaces every occurrence by default, not just the first match.
Try it yourself
function cleanText(text)
-- Write code here
end
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Table Iteration
Iterating with pairs()Iterating with ipairs()pairs() vs. ipairs()Recap - Character Sheet4Introduction to Metatables
What is a Metatable?setmetatable & getmetatableThe __index MetamethodThe __newindex MetamethodThe __tostring MetamethodArithmetic Metamethods Part 1Arithmetic Metamethods Part 2Recap - Read-Only Table7Advanced String Manipulation
string.gsub() for SubstitutionIntro to String Patternsstring.find()string.match()Iterating with string.gmatch()Recap - Log File Parser2More Table Library Functions
table.concat()table construction & unpack()table.sort()Custom Sorting with FunctionsRecap - High Score Board