String Functions
Prerequisites: Strings
The string library's functions can be called two ways:
string.upper(s) or, with method syntax, s:upper().
local s = "Hello, Lua World"
print(string.upper(s))
print(s:upper())
print(s:lower())
print(s:len())
print(s:sub(1, 5))
print(s:sub(-5))
print(s:rep(2, " | "))
print(s:reverse())
print(("x"):rep(3))
HELLO, LUA WORLD
HELLO, LUA WORLD
hello, lua world
16
Hello
World
Hello, Lua World | Hello, Lua World
dlroW auL ,olleH
xxx
s:sub(i, j)extracts charactersitoj— 1-based and inclusive. Negative positions count from the end.- A string literal needs parentheses to call a method:
("x"):rep(3).
Finding and replacing
local s = "The quick brown fox"
print(s:find("quick"))
print(s:find("slow"))
print(s:find("o", 1, true))
print(s:gsub("o", "0"))
print((s:gsub("quick", "slow")))
print(s:match("%a+$"))
5 9
nil
13 13
The quick br0wn f0x 2
The slow brown fox
fox
findreturns the start and end positions, ornil.gsubreturns the new string and the number of replacements. Wrap it in parentheses to keep only the string.find,gsub, andmatchuse patterns (%a+$means "letters at the end") — a simpler cousin of regular expressions, covered in Level 2. Passingtrueas the fourth argument tofindsearches for plain text.
Splitting and trimming
Lua has no built-in split or trim, but patterns make them one line:
local csv = "red, green ,blue"
for item in csv:gmatch("[^,]+") do
local trimmed = item:match("^%s*(.-)%s*$")
print("[" .. trimmed .. "]")
end
[red]
[green]
[blue]
gmatch loops over every match; [^,]+ means "one or more characters
that aren't commas".
Characters and codes
print(string.byte("A"))
print(string.char(72, 105))
print(("abc"):byte(1, -1))
65
Hi
97 98 99