Menu
Coddy logo textTech

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_lua

The 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: 2

Unlike 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 icon

Challenge

Easy

Write 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)

Try it yourself

function cleanText(text)
    -- Write code here
end
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online Lua compiler