lpeg.P

Converts a value into a pattern

Prototype

lpeg.P (value)

Description

Converts the given value into a proper pattern, according to the following rules:

If the argument is a pattern, it is returned unmodified.

If the argument is a string, it is translated to a pattern that matches literally the string.

eg.

lpeg.P ("You gain") --> matches "You gain"

If the argument is a non-negative number n, the result is a pattern that matches exactly n characters.

eg.

lpeg.P (5) --> matches 5 characters

If the argument is a negative number -n, the result is a pattern that succeeds only if the input string does not have n characters: It is equivalent to the unary minus operation applied over the pattern corresponding to the (non-negative) value n.

eg.

lpeg.P (-2) --> matches if there are not 2 more characters

lpeg.P (-1) --> matches if there are no more characters (ie. the end of the string)

If the argument is a boolean, the result is a pattern that always succeeds or always fails (according to the boolean value), without consuming any input.

eg.

lpeg.P (true) --> matches always
lpeg.P (false) --> matches never

If the argument is a function, returns a pattern equivalent to a match-time capture over the empty string.

If the argument is a table, it is interpreted as a grammar (see below).


-- Grammars --

With the use of Lua variables, it is possible to define patterns incrementally, with each new pattern using previously defined ones. However, this technique does not allow the definition of recursive patterns. For recursive patterns, we need real grammars.

LPeg represents grammars with tables, where each entry is a rule.

The call lpeg.V(v) creates a pattern that represents the nonterminal (or variable) with index v in a grammar. Because the grammar still does not exist when this function is evaluated, the result is an open reference to the respective rule.

A table is fixed when it is converted to a pattern (either by calling lpeg.P or by using it wherein a pattern is expected). Then every open reference created by lpeg.V(v) is corrected to refer to the rule indexed by v in the table.

When a table is fixed, the result is a pattern that matches its initial rule. The entry with index 1 in the table defines its initial rule. If that entry is a string, it is assumed to be the name of the initial rule. Otherwise, LPeg assumes that the entry 1 itself is the initial rule.

As an example, the following grammar matches strings of a's and b's that have the same number of a's and b's:

equalcount = lpeg.P{
"S"; -- initial rule name
S = "a" * lpeg.V"B" + "b" * lpeg.V"A" + "",
A = "a" * lpeg.V"S" + "b" * lpeg.V"A" * lpeg.V"A",
B = "b" * lpeg.V"S" + "a" * lpeg.V"B" * lpeg.V"B",
} * -1

Lua functions

Topics