local start_string = "3, 2, 1, go!"
-- gsub returns a new string, so calls chain
start_string = start_string
:gsub("1", "one")
:gsub("2", "two")
:gsub("3", "three")
-- start_string = three, two, one, go!
-- Replaces all occurrences and counts them
local one_string = "1 1 1"
local all_replaced, count =
one_string:gsub("1", "one")
-- all_replaced = one one one
-- count = 3
-- The 4th argument limits the count
local first_only = one_string:gsub("1", "one", 1)
-- first_only = one 1 1
-- gsub has no plain mode: the 1st argument
-- is a pattern, and "." in it is any character
local price = "1.5"
local as_pattern = price:gsub(".", ",")
-- as_pattern = ,,,
-- Written as %. the dot is only a dot
local as_text = price:gsub("%.", ",")
-- as_text = 1,5
-- In the replacement % is special too: write %%
local percents = one_string:gsub("1", "100%%")
-- percents = 100% 100% 100%
print("start_string = " .. start_string)
print("all_replaced = " .. all_replaced)
print("count = " .. count)
print("first_only = " .. first_only)
print("as_pattern = " .. as_pattern)
print("as_text = " .. as_text)
print("percents = " .. percents)