Common string functions
The string library can slice, change case, repeat and reverse text, and methods work with the colon syntax.
In this page:
Common string functions
string.sub(s, i, j) returns a slice, and negative indexes count from the end. string.upper, lower, rep and reverse do what their names say, and string.len gives the length. Every string has the string library as its metatable, so s:upper() is the same as string.upper(s).
Note:
Indexes in Lua strings start at 1, and both ends of sub are inclusive.
Example: Common string functions
local s = "Hello, Lua"
print(s:sub(1, 5), s:sub(-3), s:sub(8))
print(s:upper(), s:lower())
print(("ab"):rep(3, "-"), s:reverse())
print(s:byte(1), string.char(72, 105))
print(s:len(), s)
-- Output:
-- Hello Lua Lua
-- HELLO, LUA hello, lua
-- ab-ab-ab auL ,olleH
-- 72 Hi
-- 10 Hello, Lua
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Starting indexes at 0
- Forgetting that sub includes the end position
- Expecting upper to modify the original string
Chapter Summary
- string.sub slices with 1-based inclusive indexes
- Negative indexes count from the end
- s:upper() is the method form
- Functions return new strings
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: