Split a comma-separated list
From LuaTeXWiki
To split a comma-separated list, use the following lpeg grammar(s):
LT = { } LT.grammars = LT.grammars or { } -- Matches nested braces (a brace group) with arbitrary contents LT.grammars.braces = lpeg.P({ "{" * ((1 - lpeg.S("{}")) + lpeg.V(1))^0 * "}" }) -- Splits a list of comma-separated values into a table. Braces are -- handled correctly LT.grammars.splitComma = lpeg.P({ -- The final table capture lpeg.Ct(lpeg.V("elem") * (lpeg.V("sep") * lpeg.V("elem"))^0), -- The separator: Must contain the separator itself as well as braces sep = lpeg.S(",{}"), -- An element in the list of comma-separated values: Everything -- except the separator, or a brace group elem = lpeg.C(((1 - lpeg.V("sep")) + LT.grammars.braces)^0), })
Then "lpeg.match(splitComma,"1,2,3")" can be used to split the string into a table.