12. Strings
Strings are the values you print most. Lua has a small, handy toolkit for them: gluing, measuring, changing case, repeating, and formatting numbers into them. This chapter covers the ones you use daily.
Joining strings with ..
You have seen .. (two dots) already. It is the
concatenation operator: it returns one new string with
the second stuck onto the end of the first:
local first = "Hello, "
local second = "world!"
print(first .. second) -- Hello, world!The original variables are untouched — .. builds a new
string. You can glue text without variables too:
print("Level " .. 7 .. " complete") -- Level 7 completeA number on either side of .. becomes text
automatically. Booleans and nil do not — wrap them in
tostring() first.
Length with #
The # operator returns a string's length in bytes (the
same as its character count for plain English text):
print(#"hello") -- 5
print(#"") -- 0
local greeting = "Welcome"
print(#greeting) -- 7Use # whenever you need a string's length — for centring
text, checking input length, or building borders.
Open exercises/12/01-length.lua. Add a line that prints
the length of your own name.
Changing case
Lua's string library lives in the table string. Two
simple calls are string.upper(s) and
string.lower(s). Both return a new string
and leave the original alone:
local name = "Keiko"
print(string.upper(name)) -- KEIKO
print(string.lower(name)) -- keiko
print(name) -- Keiko (still the original)Repeating a string
string.rep(s, n) returns the string s
repeated n times:
print(string.rep("-", 20)) -- --------------------
print(string.rep("ab", 3)) -- ababab
print(string.rep("=", 4) .. " TITLE " .. string.rep("=", 4))
-- ==== TITLE ====It is the right tool for drawing borders or padding text.
Formatting with
string.format
When you need numbers or text plugged into specific spots,
string.format beats a long chain of ... The
first argument is a template with placeholders starting
with %; the rest fill them in order:
local name = "Keiko"
local level = 7
local hp = 95
print(string.format("%s (Lv %d) HP %d", name, level, hp))
-- Keiko (Lv 7) HP 95The placeholders you need today:
| Placeholder | What it expects | Example output |
|---|---|---|
%s |
a string | Keiko |
%d |
a whole number | 7 |
%.2f |
a decimal with two digits after the point | 3.14 |
There are many more, but those three cover most everyday uses. The
full list is in the Lua reference manual under
string.format.
Open exercises/12/02-format.lua. Change the format
string so the output reads Keiko has 95 HP at level 7.
Escape sequences
Some characters are awkward in a string because they collide with
Lua's punctuation. The fix is an escape sequence — a
backslash \ followed by a letter, which Lua replaces with
the special character:
| Sequence | What it becomes |
|---|---|
\n |
a newline (move to next line) |
\t |
a tab |
\" |
a literal double quote |
\' |
a literal single quote |
\\ |
a literal backslash |
Example:
print("Line 1\nLine 2\nLine 3")
-- Line 1
-- Line 2
-- Line 3
print("Name\tLevel\tHP")
-- Name Level HP
print("She said \"hi\" and waved.")
-- She said "hi" and waved.Multi-line strings
When a string spans many lines with lots of quotes, escape sequences
get noisy. Lua offers another way: [[ to open and
]] to close. Anything between them is the string, including
newlines and quotes:
local poem = [[
Roses are red,
Violets are blue,
"Pick a number,"
said the program to you.
]]
print(poem)Once created, multi-line strings are just regular strings — a friendlier way to write them.
You met [[ ]] before, in --[[ ]] for
multi-line comments. Same idea — Lua reads everything
between the brackets as one block. The -- in front is what
turns a multi-line string into a multi-line comment.
Homework
Problem 1 — Loud and quiet
Open exercises/12/homework/01-loud-and-quiet.lua. A
starter variable holds your name. Print it three times: as-is, in upper
case, then in lower case.
Problem 2 — Stat line
Open exercises/12/homework/02-stat-line.lua. Three
variables are declared at the top: a string name, a number level, a
number hp. Using string.format, print one line in this
exact shape:
Keiko Lv 7 HP 95
The labels (Lv, HP) and the spacing between
fields can be literal spaces inside the format string.
Problem 3 — One-line three-line poem
Open exercises/12/homework/03-three-line-poem.lua. Print
a three line poem using exactly one print
call. The line breaks must come from \n inside the string.
Add a -- comment after the print call explaining why one
print can produce three lines.
Challenge — Title block
Open exercises/12/homework/04-title-block.lua. A
variable holds a title (any string you like). Print a block like this,
where the top and bottom dash rows match the title's length plus two
dashes on each side:
----- INVENTORY -----
Inside text goes here
----- INVENTORY -----
Use string.rep and # to size the borders
without counting by hand. Changing the title should change the border
length automatically.
Stuck or finished? Open the homework solutions page.