lpeg.Cg

Creates a group capture

Prototype

lpeg.Cg (patt [, name])

Description

It groups all values returned by patt into a single capture. The group may be anonymous (if no name is given) or named with the given name.

An anonymous group serves to join values from several captures into a single capture. A named group has a different behavior. In most situations, a named group returns no values at all. Its values are only relevant for a following back capture or when used inside a table capture.

This example parses a list of name-value pairs and returns a table with those pairs:

lpeg.locale(lpeg)

local space = lpeg.space^0
local name = lpeg.C(lpeg.alpha^1) * space
local sep = lpeg.S(",;") * space
local pair = lpeg.Cg(name * "=" * space * name) * sep^-1
local list = lpeg.Cf(lpeg.Ct("") * pair^0, rawset)
t = list:match("a=b, c = hi; next = pi") --> { a = "b", c = "hi", next = "pi" }

Each pair has the format name = name followed by an optional separator (a comma or a semicolon). The pair pattern encloses the pair in a group pattern, so that the names become the values of a single capture. The list pattern then folds these captures. It starts with an empty table, created by a table capture matching an empty string; then for each capture (a pair of names) it applies rawset over the accumulator (the table) and the capture values (the pair of names). rawset returns the table itself, so the accumulator is always the table.

Lua functions

Topics