← Back to Lua Course | Chapter 3: Strings | Lesson 3 of 7

Common string functions

The string library can slice, change case, repeat and reverse text, and methods work with the colon syntax.

In this page:

  1. Common string functions

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

lua
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
Common Mistakes
  1. Starting indexes at 0
  2. Forgetting that sub includes the end position
  3. 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

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.