110 CHAPTER 5 Scripting
A modifier character describing how often a character of that class is
expected can follow a character class sequence:
none Exactly one occurrence
+ At least one occurrence
* Any number of occurrences; works greedily (tries to consume longest
sequence possible to succeed)
- Any number of occurrences; works non-greedily (tries to consume short-
est sequence possible to succeed)
? Optional (0 or 1 occurrence)
Command sequences that match a character sequence can be captured,
meaning that the matching character string will be accessible. A capture is
achieved by putting a command sequence into parentheses. The matching
character sequence is then delivered as an extra result by the find() func-
tion. For example:
_, _, m, d, y = string.find(
"9/25/2009", "(%d+)/(%d+)/(%d+)")
assigns 9 to m, 25 to d, 2009 to y. Each capture (%d+) tries to find one or
more digits until the next slash or the end of the string, and it delivers the
matching substring as a result.
Capture results can be used in the pattern itself or in the substitution
string of the gsub() function. They are symbolized by the control sequences
%1, %2, .... representing the result of the first capture, the second capture,
and so on. For example:
string.gsub("log.txt",
"(%w+)%.(%w+)", "%1_1.%2")
would result in “log_1.txt”.
Table manipulation functions
Because tables are an essential construct in Lua, there is also a standard
library with functions for conveniently manipulating them.
s = table.concat(table,sep,i,j)
Concatenates the table elements i..j into a string, each separated by separator
sep—provided all elements are strings or numbers. sep, if omitted, defaults to the
empty string. i and j default, if omitted, to 1 resp. the length of the table.