String Functions and Colon Calls

In the Basics section you learned .. to join strings and # to get their length. Lua has many more string functions. They live in the string library, so their full names are string.upper, string.sub and so on.

local s = "strawberry"
print(string.upper(s))
print(s:upper())

Output:

STRAWBERRY
STRAWBERRY

Both lines do the same thing. The second one uses a colon call: s:upper() means "call string.upper and pass s as the first argument". It is shorter, and it is how most Lua code is written, so this course uses it from now on. You will see where the colon comes from in the Going Further section.

Changing case

local s = "Hello Lua"
print(s:upper())
print(s:lower())
print(s)

Output:

HELLO LUA
hello lua
Hello Lua

upper makes every letter a capital, and lower makes every letter small. Look at the last line: s did not change. Lua strings can never be changed. These functions always give you a new string.

Cutting out a part with sub

sub(from, to) returns the characters from position from to position to. Both ends are included, and the first character is at position 1, like table indexes.

local s = "strawberry"
print(s:sub(1, 5))
print(s:sub(1, 1))
print(s:sub(-5))
print(s:sub(-3))

Output:

straw
s
berry
rry

A negative position counts from the end: -1 is the last character. When you leave out to, sub goes to the end of the string. So s:sub(-3) means "the last three characters".

Repeating with rep

rep(n) repeats a string n times. You can also call one function on the result of another, in one line:

local s = "strawberry"
print(("ab"):rep(3))
print(s:sub(1, 5):rep(2))

Output:

ababab
strawstraw

The second line runs from left to right. First s:sub(1, 5) gives straw, then :rep(2) repeats that. A string written directly in the code needs parentheses around it before a colon call, like ("ab"):rep(3).

Searching inside text (find, match and gsub) is the topic of the next lesson.

In the exercise, read a word and print it in capitals, its first letter, and its first three letters twice.