Split a comma-separated list

From LuaTeXWiki
Revision as of 22:17, 7 December 2010 by Patrick (talk | contribs) (Copied from the old bluwiki.com luatex wiki)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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.