Lua, lesson 8
Lua strings are immutable: every string function returns a new string. The functions live
in the string table, and you can call them two ways. string.upper(s) and s:upper() mean
the same thing; the colon form passes s as the first argument and is the usual style.
Like tables, string positions start at 1. # and sub count bytes, which is the same as
characters for plain ASCII text.
Lua doesn't include full regular expressions. It has its own smaller patterns, which
cover most everyday needs. In a pattern, % introduces a character class:
2 exercises to try what you just read.
| Class | Matches |
|---|
%a | a letter |
%d | a digit |
%s | whitespace |
%w | a letter or digit |
%S, %A, … | uppercase means "anything except" |
. | any character |
Add + for "one or more", * for "zero or more", and - for "zero or more, as few as
possible". Parentheses capture the part they surround.
Four functions use patterns:
gmatch("%S+") is the standard way to split a line into words.
Because gsub returns two values, wrap the call in parentheses when you only want the
string: print((s:gsub("a", "b"))).
Joining strings with .. inside a loop creates many temporary strings. For anything longer
than a few pieces, collect the pieces in a table and join them once with table.concat.
string.format pads and aligns: %-8s left-aligns a string in 8 columns, %5d right-aligns
an integer in 5, and %.1f keeps one decimal:
The last exercise is a small project that uses everything in this course: reading input, patterns, decisions, a loop, a helper function, a table of records, and formatted output. A good plan:
{name = "Ada", score = 95}.Read one line of text and print four lines:
For the palindrome test, ignore case and ignore every character that is not a letter. So
Never odd or even counts as a palindrome.
Sample input:
Sample output:
Time for a small project. The first input line is the number of students (at least 1). Each following line has a student's name and a whole-number score from 0 to 100, separated by a space.
Grades: 90 or more is A, 80 or more is B, 70 or more is C, 60 or more is D, anything
lower is F.
Print one line per student in input order, <name>: <score> (<grade>). Then print the
average score with one decimal place, and the name of the top student. If several students
share the top score, print the one who appears first.
Sample input:
Sample output:
local s = "Hello, Lua"
print(#s) -- 10 (length in bytes)
print(s:upper()) -- HELLO, LUA
print(s:lower()) -- hello, lua
print(s:sub(1, 5)) -- Hello (positions 1 to 5, both included)
print(s:sub(-3)) -- Lua (negative positions count from the end)
print(s:reverse()) -- auL ,olleH
print(s:rep(2, "|")) -- Hello, Lua|Hello, Lua
print(s:byte(1)) -- 72 (character code)-- find: where does it occur?
print(("banana"):find("an")) -- 2 3
-- match: return the captured pieces
local item, qty = ("milk 2"):match("(%S+)%s+(%d+)") -- "milk", "2"
-- gsub: replace every match; also returns how many it replaced
print(("a-b-c"):gsub("-", "+")) -- a+b+c 2
local digits = ("R2-D2"):gsub("%D", "") -- "22"
-- gmatch: loop over every match
for word in ("red green blue"):gmatch("%a+") do
print(word)
endprint(string.format("%-8s|%5d|", "Ada", 95)) -- Ada | 95|Upper: <the line in uppercase>
Reversed: <the line reversed>
Length: <number of characters in the line>
Palindrome: <yes or no>Never odd or evenUpper: NEVER ODD OR EVEN
Reversed: neve ro ddo reveN
Length: 17
Palindrome: yes3
Ada 95
Ben 72
Cleo 88Ada: 95 (A)
Ben: 72 (C)
Cleo: 88 (B)
Average: 85.0
Top: Ada