lpeg.html 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  2. "//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  3. <html xmlns="//www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  4. <head>
  5. <title>LPeg - Parsing Expression Grammars For Lua</title>
  6. <link rel="stylesheet"
  7. href="//www.inf.puc-rio.br/~roberto/lpeg/doc.css"
  8. type="text/css"/>
  9. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  10. </head>
  11. <body>
  12. <div id="container">
  13. <div id="product">
  14. <div id="product_logo">
  15. <a href="//www.inf.puc-rio.br/~roberto/lpeg/">
  16. <img alt="LPeg logo" src="lpeg-128.gif"/></a>
  17. </div>
  18. <div id="product_name"><big><strong>LPeg</strong></big></div>
  19. <div id="product_description">
  20. Parsing Expression Grammars For Lua, version 1.1
  21. </div>
  22. </div> <!-- id="product" -->
  23. <div id="main">
  24. <div id="navigation">
  25. <h1>LPeg</h1>
  26. <ul>
  27. <li><strong>Home</strong>
  28. <ul>
  29. <li><a href="#intro">Introduction</a></li>
  30. <li><a href="#func">Functions</a></li>
  31. <li><a href="#basic">Basic Constructions</a></li>
  32. <li><a href="#grammar">Grammars</a></li>
  33. <li><a href="#captures">Captures</a></li>
  34. <li><a href="#ex">Some Examples</a></li>
  35. <li><a href="re.html">The <code>re</code> Module</a></li>
  36. <li><a href="#download">Download</a></li>
  37. <li><a href="#license">License</a></li>
  38. </ul>
  39. </li>
  40. </ul>
  41. </div> <!-- id="navigation" -->
  42. <div id="content">
  43. <h2><a name="intro">Introduction</a></h2>
  44. <p>
  45. <em>LPeg</em> is a new pattern-matching library for Lua,
  46. based on
  47. <a href="//bford.info/packrat/">
  48. Parsing Expression Grammars</a> (PEGs).
  49. This text is a reference manual for the library.
  50. For a more formal treatment of LPeg,
  51. as well as some discussion about its implementation,
  52. see
  53. <a href="//www.inf.puc-rio.br/~roberto/docs/peg.pdf">
  54. A Text Pattern-Matching Tool based on Parsing Expression Grammars</a>.
  55. (You may also be interested in my
  56. <a href="//vimeo.com/1485123">talk about LPeg</a>
  57. given at the III Lua Workshop.)
  58. </p>
  59. <p>
  60. Following the Snobol tradition,
  61. LPeg defines patterns as first-class objects.
  62. That is, patterns are regular Lua values
  63. (represented by userdata).
  64. The library offers several functions to create
  65. and compose patterns.
  66. With the use of metamethods,
  67. several of these functions are provided as infix or prefix
  68. operators.
  69. On the one hand,
  70. the result is usually much more verbose than the typical
  71. encoding of patterns using the so called
  72. <em>regular expressions</em>
  73. (which typically are not regular expressions in the formal sense).
  74. On the other hand,
  75. first-class patterns allow much better documentation
  76. (as it is easy to comment the code,
  77. to break complex definitions in smaller parts, etc.)
  78. and are extensible,
  79. as we can define new functions to create and compose patterns.
  80. </p>
  81. <p>
  82. For a quick glance of the library,
  83. the following table summarizes its basic operations
  84. for creating patterns:
  85. </p>
  86. <table border="1">
  87. <tbody><tr><td><b>Operator</b></td><td><b>Description</b></td></tr>
  88. <tr><td><a href="#op-p"><code>lpeg.P(string)</code></a></td>
  89. <td>Matches <code>string</code> literally</td></tr>
  90. <tr><td><a href="#op-p"><code>lpeg.P(n)</code></a></td>
  91. <td>Matches exactly <code>n</code> characters</td></tr>
  92. <tr><td><a href="#op-s"><code>lpeg.S(string)</code></a></td>
  93. <td>Matches any character in <code>string</code> (Set)</td></tr>
  94. <tr><td><a href="#op-r"><code>lpeg.R("<em>xy</em>")</code></a></td>
  95. <td>Matches any character between <em>x</em> and <em>y</em> (Range)</td></tr>
  96. <tr><td><a href="#op-utfR"><code>lpeg.utfR(cp1, cp2)</code></a></td>
  97. <td>Matches an UTF-8 code point between <code>cp1</code> and
  98. <code>cp2</code></td></tr>
  99. <tr><td><a href="#op-pow"><code>patt^n</code></a></td>
  100. <td>Matches at least <code>n</code> repetitions of <code>patt</code></td></tr>
  101. <tr><td><a href="#op-pow"><code>patt^-n</code></a></td>
  102. <td>Matches at most <code>n</code> repetitions of <code>patt</code></td></tr>
  103. <tr><td><a href="#op-mul"><code>patt1 * patt2</code></a></td>
  104. <td>Matches <code>patt1</code> followed by <code>patt2</code></td></tr>
  105. <tr><td><a href="#op-add"><code>patt1 + patt2</code></a></td>
  106. <td>Matches <code>patt1</code> or <code>patt2</code>
  107. (ordered choice)</td></tr>
  108. <tr><td><a href="#op-sub"><code>patt1 - patt2</code></a></td>
  109. <td>Matches <code>patt1</code> if <code>patt2</code> does not match</td></tr>
  110. <tr><td><a href="#op-unm"><code>-patt</code></a></td>
  111. <td>Equivalent to <code>("" - patt)</code></td></tr>
  112. <tr><td><a href="#op-len"><code>#patt</code></a></td>
  113. <td>Matches <code>patt</code> but consumes no input</td></tr>
  114. <tr><td><a href="#op-behind"><code>lpeg.B(patt)</code></a></td>
  115. <td>Matches <code>patt</code> behind the current position,
  116. consuming no input</td></tr>
  117. </tbody></table>
  118. <p>As a very simple example,
  119. <code>lpeg.R("09")^1</code> creates a pattern that
  120. matches a non-empty sequence of digits.
  121. As a not so simple example,
  122. <code>-lpeg.P(1)</code>
  123. (which can be written as <code>lpeg.P(-1)</code>,
  124. or simply <code>-1</code> for operations expecting a pattern)
  125. matches an empty string only if it cannot match a single character;
  126. so, it succeeds only at the end of the subject.
  127. </p>
  128. <p>
  129. LPeg also offers the <a href="re.html"><code>re</code> module</a>,
  130. which implements patterns following a regular-expression style
  131. (e.g., <code>[09]+</code>).
  132. (This module is 270 lines of Lua code,
  133. and of course it uses LPeg to parse regular expressions and
  134. translate them to regular LPeg patterns.)
  135. </p>
  136. <h2><a name="func">Functions</a></h2>
  137. <h3><a name="f-match"></a><code>lpeg.match (pattern, subject [, init])</code></h3>
  138. <p>
  139. The matching function.
  140. It attempts to match the given pattern against the subject string.
  141. If the match succeeds,
  142. returns the index in the subject of the first character after the match,
  143. or the <a href="#captures">captured values</a>
  144. (if the pattern captured any value).
  145. </p>
  146. <p>
  147. An optional numeric argument <code>init</code> makes the match
  148. start at that position in the subject string.
  149. As in the Lua standard libraries,
  150. a negative value counts from the end.
  151. </p>
  152. <p>
  153. Unlike typical pattern-matching functions,
  154. <code>match</code> works only in <em>anchored</em> mode;
  155. that is, it tries to match the pattern with a prefix of
  156. the given subject string (at position <code>init</code>),
  157. not with an arbitrary substring of the subject.
  158. So, if we want to find a pattern anywhere in a string,
  159. we must either write a loop in Lua or write a pattern that
  160. matches anywhere.
  161. This second approach is easy and quite efficient;
  162. see <a href="#ex">examples</a>.
  163. </p>
  164. <h3><a name="f-type"></a><code>lpeg.type (value)</code></h3>
  165. <p>
  166. If the given value is a pattern,
  167. returns the string <code>"pattern"</code>.
  168. Otherwise returns nil.
  169. </p>
  170. <h3><a name="f-version"></a><code>lpeg.version</code></h3>
  171. <p>
  172. A string (not a function) with the running version of LPeg.
  173. </p>
  174. <h3><a name="f-setstack"></a><code>lpeg.setmaxstack (max)</code></h3>
  175. <p>
  176. Sets a limit for the size of the backtrack stack used by LPeg to
  177. track calls and choices.
  178. (The default limit is 400.)
  179. Most well-written patterns need little backtrack levels and
  180. therefore you seldom need to change this limit;
  181. before changing it you should try to rewrite your
  182. pattern to avoid the need for extra space.
  183. Nevertheless, a few useful patterns may overflow.
  184. Also, with recursive grammars,
  185. subjects with deep recursion may also need larger limits.
  186. </p>
  187. <h2><a name="basic">Basic Constructions</a></h2>
  188. <p>
  189. The following operations build patterns.
  190. All operations that expect a pattern as an argument
  191. may receive also strings, tables, numbers, booleans, or functions,
  192. which are translated to patterns according to
  193. the rules of function <a href="#op-p"><code>lpeg.P</code></a>.
  194. </p>
  195. <h3><a name="op-p"></a><code>lpeg.P (value)</code></h3>
  196. <p>
  197. Converts the given value into a proper pattern,
  198. according to the following rules:
  199. </p>
  200. <ul>
  201. <li><p>
  202. If the argument is a pattern,
  203. it is returned unmodified.
  204. </p></li>
  205. <li><p>
  206. If the argument is a string,
  207. it is translated to a pattern that matches the string literally.
  208. </p></li>
  209. <li><p>
  210. If the argument is a non-negative number <em>n</em>,
  211. the result is a pattern that matches exactly <em>n</em> characters.
  212. </p></li>
  213. <li><p>
  214. If the argument is a negative number <em>-n</em>,
  215. the result is a pattern that
  216. succeeds only if the input string has less than <em>n</em> characters left:
  217. <code>lpeg.P(-n)</code>
  218. is equivalent to <code>-lpeg.P(n)</code>
  219. (see the <a href="#op-unm">unary minus operation</a>).
  220. </p></li>
  221. <li><p>
  222. If the argument is a boolean,
  223. the result is a pattern that always succeeds or always fails
  224. (according to the boolean value),
  225. without consuming any input.
  226. </p></li>
  227. <li><p>
  228. If the argument is a table,
  229. it is interpreted as a grammar
  230. (see <a href="#grammar">Grammars</a>).
  231. </p></li>
  232. <li><p>
  233. If the argument is a function,
  234. returns a pattern equivalent to a
  235. <a href="#matchtime">match-time capture</a> over the empty string.
  236. </p></li>
  237. </ul>
  238. <h3><a name="op-behind"></a><code>lpeg.B(patt)</code></h3>
  239. <p>
  240. Returns a pattern that
  241. matches only if the input string at the current position
  242. is preceded by <code>patt</code>.
  243. Pattern <code>patt</code> must match only strings
  244. with some fixed length,
  245. and it cannot contain captures.
  246. </p>
  247. <p>
  248. Like the <a href="#op-len">and predicate</a>,
  249. this pattern never consumes any input,
  250. independently of success or failure.
  251. </p>
  252. <h3><a name="op-r"></a><code>lpeg.R ({range})</code></h3>
  253. <p>
  254. Returns a pattern that matches any single character
  255. belonging to one of the given <em>ranges</em>.
  256. Each <code>range</code> is a string <em>xy</em> of length 2,
  257. representing all characters with code
  258. between the codes of <em>x</em> and <em>y</em>
  259. (both inclusive).
  260. </p>
  261. <p>
  262. As an example, the pattern
  263. <code>lpeg.R("09")</code> matches any digit,
  264. and <code>lpeg.R("az", "AZ")</code> matches any ASCII letter.
  265. </p>
  266. <h3><a name="op-s"></a><code>lpeg.S (string)</code></h3>
  267. <p>
  268. Returns a pattern that matches any single character that
  269. appears in the given string.
  270. (The <code>S</code> stands for <em>Set</em>.)
  271. </p>
  272. <p>
  273. As an example, the pattern
  274. <code>lpeg.S("+-*/")</code> matches any arithmetic operator.
  275. </p>
  276. <p>
  277. Note that, if <code>s</code> is a character
  278. (that is, a string of length 1),
  279. then <code>lpeg.P(s)</code> is equivalent to <code>lpeg.S(s)</code>
  280. which is equivalent to <code>lpeg.R(s..s)</code>.
  281. Note also that both <code>lpeg.S("")</code> and <code>lpeg.R()</code>
  282. are patterns that always fail.
  283. </p>
  284. <h3><a name="op-utfR"></a><code>lpeg.utfR (cp1, cp2)</code></h3>
  285. <p>
  286. Returns a pattern that matches a valid UTF-8 byte sequence
  287. representing a code point in the range <code>[cp1, cp2]</code>.
  288. The range is limited by the natural Unicode limit of 0x10FFFF,
  289. but may include surrogates.
  290. </p>
  291. <h3><a name="op-v"></a><code>lpeg.V (v)</code></h3>
  292. <p>
  293. This operation creates a non-terminal (a <em>variable</em>)
  294. for a grammar.
  295. The created non-terminal refers to the rule indexed by <code>v</code>
  296. in the enclosing grammar.
  297. (See <a href="#grammar">Grammars</a> for details.)
  298. </p>
  299. <h3><a name="op-locale"></a><code>lpeg.locale ([table])</code></h3>
  300. <p>
  301. Returns a table with patterns for matching some character classes
  302. according to the current locale.
  303. The table has fields named
  304. <code>alnum</code>,
  305. <code>alpha</code>,
  306. <code>cntrl</code>,
  307. <code>digit</code>,
  308. <code>graph</code>,
  309. <code>lower</code>,
  310. <code>print</code>,
  311. <code>punct</code>,
  312. <code>space</code>,
  313. <code>upper</code>, and
  314. <code>xdigit</code>,
  315. each one containing a correspondent pattern.
  316. Each pattern matches any single character that belongs to its class.
  317. </p>
  318. <p>
  319. If called with an argument <code>table</code>,
  320. then it creates those fields inside the given table and
  321. returns that table.
  322. </p>
  323. <h3><a name="op-len"></a><code>#patt</code></h3>
  324. <p>
  325. Returns a pattern that
  326. matches only if the input string matches <code>patt</code>,
  327. but without consuming any input,
  328. independently of success or failure.
  329. (This pattern is called an <em>and predicate</em>
  330. and it is equivalent to
  331. <em>&amp;patt</em> in the original PEG notation.)
  332. </p>
  333. <p>
  334. This pattern never produces any capture.
  335. </p>
  336. <h3><a name="op-unm"></a><code>-patt</code></h3>
  337. <p>
  338. Returns a pattern that
  339. matches only if the input string does not match <code>patt</code>.
  340. It does not consume any input,
  341. independently of success or failure.
  342. (This pattern is equivalent to
  343. <em>!patt</em> in the original PEG notation.)
  344. </p>
  345. <p>
  346. As an example, the pattern
  347. <code>-lpeg.P(1)</code> matches only the end of string.
  348. </p>
  349. <p>
  350. This pattern never produces any captures,
  351. because either <code>patt</code> fails
  352. or <code>-patt</code> fails.
  353. (A failing pattern never produces captures.)
  354. </p>
  355. <h3><a name="op-add"></a><code>patt1 + patt2</code></h3>
  356. <p>
  357. Returns a pattern equivalent to an <em>ordered choice</em>
  358. of <code>patt1</code> and <code>patt2</code>.
  359. (This is denoted by <em>patt1 / patt2</em> in the original PEG notation,
  360. not to be confused with the <code>/</code> operation in LPeg.)
  361. It matches either <code>patt1</code> or <code>patt2</code>,
  362. with no backtracking once one of them succeeds.
  363. The identity element for this operation is the pattern
  364. <code>lpeg.P(false)</code>,
  365. which always fails.
  366. </p>
  367. <p>
  368. If both <code>patt1</code> and <code>patt2</code> are
  369. character sets,
  370. this operation is equivalent to set union.
  371. </p>
  372. <pre class="example">
  373. lower = lpeg.R("az")
  374. upper = lpeg.R("AZ")
  375. letter = lower + upper
  376. </pre>
  377. <h3><a name="op-sub"></a><code>patt1 - patt2</code></h3>
  378. <p>
  379. Returns a pattern equivalent to <em>!patt2 patt1</em>
  380. in the origial PEG notation.
  381. This pattern asserts that the input does not match
  382. <code>patt2</code> and then matches <code>patt1</code>.
  383. </p>
  384. <p>
  385. When successful,
  386. this pattern produces all captures from <code>patt1</code>.
  387. It never produces any capture from <code>patt2</code>
  388. (as either <code>patt2</code> fails or
  389. <code>patt1 - patt2</code> fails).
  390. </p>
  391. <p>
  392. If both <code>patt1</code> and <code>patt2</code> are
  393. character sets,
  394. this operation is equivalent to set difference.
  395. Note that <code>-patt</code> is equivalent to <code>"" - patt</code>
  396. (or <code>0 - patt</code>).
  397. If <code>patt</code> is a character set,
  398. <code>1 - patt</code> is its complement.
  399. </p>
  400. <h3><a name="op-mul"></a><code>patt1 * patt2</code></h3>
  401. <p>
  402. Returns a pattern that matches <code>patt1</code>
  403. and then matches <code>patt2</code>,
  404. starting where <code>patt1</code> finished.
  405. The identity element for this operation is the
  406. pattern <code>lpeg.P(true)</code>,
  407. which always succeeds.
  408. </p>
  409. <p>
  410. (LPeg uses the <code>*</code> operator
  411. [instead of the more obvious <code>..</code>]
  412. both because it has
  413. the right priority and because in formal languages it is
  414. common to use a dot for denoting concatenation.)
  415. </p>
  416. <h3><a name="op-pow"></a><code>patt^n</code></h3>
  417. <p>
  418. If <code>n</code> is nonnegative,
  419. this pattern is
  420. equivalent to <em>patt<sup>n</sup> patt*</em>:
  421. It matches <code>n</code> or more occurrences of <code>patt</code>.
  422. </p>
  423. <p>
  424. Otherwise, when <code>n</code> is negative,
  425. this pattern is equivalent to <em>(patt?)<sup>-n</sup></em>:
  426. It matches at most <code>|n|</code>
  427. occurrences of <code>patt</code>.
  428. </p>
  429. <p>
  430. In particular, <code>patt^0</code> is equivalent to <em>patt*</em>,
  431. <code>patt^1</code> is equivalent to <em>patt+</em>,
  432. and <code>patt^-1</code> is equivalent to <em>patt?</em>
  433. in the original PEG notation.
  434. </p>
  435. <p>
  436. In all cases,
  437. the resulting pattern is greedy with no backtracking
  438. (also called a <em>possessive</em> repetition).
  439. That is, it matches only the longest possible sequence
  440. of matches for <code>patt</code>.
  441. </p>
  442. <h2><a name="grammar">Grammars</a></h2>
  443. <p>
  444. With the use of Lua variables,
  445. it is possible to define patterns incrementally,
  446. with each new pattern using previously defined ones.
  447. However, this technique does not allow the definition of
  448. recursive patterns.
  449. For recursive patterns,
  450. we need real grammars.
  451. </p>
  452. <p>
  453. LPeg represents grammars with tables,
  454. where each entry is a rule.
  455. </p>
  456. <p>
  457. The call <code>lpeg.V(v)</code>
  458. creates a pattern that represents the nonterminal
  459. (or <em>variable</em>) with index <code>v</code> in a grammar.
  460. Because the grammar still does not exist when
  461. this function is evaluated,
  462. the result is an <em>open reference</em> to the respective rule.
  463. </p>
  464. <p>
  465. A table is <em>fixed</em> when it is converted to a pattern
  466. (either by calling <code>lpeg.P</code> or by using it wherein a
  467. pattern is expected).
  468. Then every open reference created by <code>lpeg.V(v)</code>
  469. is corrected to refer to the rule indexed by <code>v</code> in the table.
  470. </p>
  471. <p>
  472. When a table is fixed,
  473. the result is a pattern that matches its <em>initial rule</em>.
  474. The entry with index 1 in the table defines its initial rule.
  475. If that entry is a string,
  476. it is assumed to be the name of the initial rule.
  477. Otherwise, LPeg assumes that the entry 1 itself is the initial rule.
  478. </p>
  479. <p>
  480. As an example,
  481. the following grammar matches strings of a's and b's that
  482. have the same number of a's and b's:
  483. </p>
  484. <pre class="example">
  485. equalcount = lpeg.P{
  486. "S"; -- initial rule name
  487. S = "a" * lpeg.V"B" + "b" * lpeg.V"A" + "",
  488. A = "a" * lpeg.V"S" + "b" * lpeg.V"A" * lpeg.V"A",
  489. B = "b" * lpeg.V"S" + "a" * lpeg.V"B" * lpeg.V"B",
  490. } * -1
  491. </pre>
  492. <p>
  493. It is equivalent to the following grammar in standard PEG notation:
  494. </p>
  495. <pre class="example">
  496. S <- 'a' B / 'b' A / ''
  497. A <- 'a' S / 'b' A A
  498. B <- 'b' S / 'a' B B
  499. </pre>
  500. <h2><a name="captures">Captures</a></h2>
  501. <p>
  502. A <em>capture</em> is a pattern that produces values
  503. (the so called <em>semantic information</em>)
  504. according to what it matches.
  505. LPeg offers several kinds of captures,
  506. which produces values based on matches and combine these values to
  507. produce new values.
  508. Each capture may produce zero or more values.
  509. </p>
  510. <p>
  511. The following table summarizes the basic captures:
  512. </p>
  513. <table border="1">
  514. <tbody><tr><td><b>Operation</b></td><td><b>What it Produces</b></td></tr>
  515. <tr><td><a href="#cap-c"><code>lpeg.C(patt)</code></a></td>
  516. <td>the match for <code>patt</code> plus all captures
  517. made by <code>patt</code></td></tr>
  518. <tr><td><a href="#cap-arg"><code>lpeg.Carg(n)</code></a></td>
  519. <td>the value of the n<sup>th</sup> extra argument to
  520. <code>lpeg.match</code> (matches the empty string)</td></tr>
  521. <tr><td><a href="#cap-b"><code>lpeg.Cb(key)</code></a></td>
  522. <td>the values produced by the previous
  523. group capture named <code>key</code>
  524. (matches the empty string)</td></tr>
  525. <tr><td><a href="#cap-cc"><code>lpeg.Cc(values)</code></a></td>
  526. <td>the given values (matches the empty string)</td></tr>
  527. <tr><td><a href="#cap-f"><code>lpeg.Cf(patt, func)</code></a></td>
  528. <td>folding capture (<em>deprecated</em>)</td></tr>
  529. <tr><td><a href="#cap-g"><code>lpeg.Cg(patt [, key])</code></a></td>
  530. <td>the values produced by <code>patt</code>,
  531. optionally tagged with <code>key</code></td></tr>
  532. <tr><td><a href="#cap-p"><code>lpeg.Cp()</code></a></td>
  533. <td>the current position (matches the empty string)</td></tr>
  534. <tr><td><a href="#cap-s"><code>lpeg.Cs(patt)</code></a></td>
  535. <td>the match for <code>patt</code>
  536. with the values from nested captures replacing their matches</td></tr>
  537. <tr><td><a href="#cap-t"><code>lpeg.Ct(patt)</code></a></td>
  538. <td>a table with all captures from <code>patt</code></td></tr>
  539. <tr><td><a href="#cap-string"><code>patt / string</code></a></td>
  540. <td><code>string</code>, with some marks replaced by captures
  541. of <code>patt</code></td></tr>
  542. <tr><td><a href="#cap-num"><code>patt / number</code></a></td>
  543. <td>the n-th value captured by <code>patt</code>,
  544. or no value when <code>number</code> is zero.</td></tr>
  545. <tr><td><a href="#cap-query"><code>patt / table</code></a></td>
  546. <td><code>table[c]</code>, where <code>c</code> is the (first)
  547. capture of <code>patt</code></td></tr>
  548. <tr><td><a href="#cap-func"><code>patt / function</code></a></td>
  549. <td>the returns of <code>function</code> applied to the captures
  550. of <code>patt</code></td></tr>
  551. <tr><td><a href="#cap-acc"><code>patt % function</code></a></td>
  552. <td>produces no value;
  553. it <em>accummulates</em> the captures from <code>patt</code>
  554. into the previous capture through <code>function</code>
  555. </td></tr>
  556. <tr><td><a href="#matchtime"><code>lpeg.Cmt(patt, function)</code></a></td>
  557. <td>the returns of <code>function</code> applied to the captures
  558. of <code>patt</code>; the application is done at match time</td></tr>
  559. </tbody></table>
  560. <p>
  561. A capture pattern produces its values only when it succeeds.
  562. For instance,
  563. the pattern <code>lpeg.C(lpeg.P"a"^-1)</code>
  564. produces the empty string when there is no <code>"a"</code>
  565. (because the pattern <code>"a"?</code> succeeds),
  566. while the pattern <code>lpeg.C("a")^-1</code>
  567. does not produce any value when there is no <code>"a"</code>
  568. (because the pattern <code>"a"</code> fails).
  569. A pattern inside a loop or inside a recursive structure
  570. produces values for each match.
  571. </p>
  572. <p>
  573. Usually,
  574. LPeg does not specify when (and if) it evaluates its captures.
  575. (As an example,
  576. consider the pattern <code>lpeg.P"a" / func / 0</code>.
  577. Because the "division" by 0 instructs LPeg to throw away the
  578. results from the pattern,
  579. it is not specified whether LPeg will call <code>func</code>.)
  580. Therefore, captures should avoid side effects.
  581. Moreover,
  582. captures cannot affect the way a pattern matches a subject.
  583. The only exception to this rule is the
  584. so-called <a href="#matchtime"><em>match-time capture</em></a>.
  585. When a match-time capture matches,
  586. it forces the immediate evaluation of all its nested captures
  587. and then calls its corresponding function,
  588. which defines whether the match succeeds and also
  589. what values are produced.
  590. </p>
  591. <h3><a name="cap-c"></a><code>lpeg.C (patt)</code></h3>
  592. <p>
  593. Creates a <em>simple capture</em>,
  594. which captures the substring of the subject that matches <code>patt</code>.
  595. The captured value is a string.
  596. If <code>patt</code> has other captures,
  597. their values are returned after this one.
  598. </p>
  599. <h3><a name="cap-arg"></a><code>lpeg.Carg (n)</code></h3>
  600. <p>
  601. Creates an <em>argument capture</em>.
  602. This pattern matches the empty string and
  603. produces the value given as the n<sup>th</sup> extra
  604. argument given in the call to <code>lpeg.match</code>.
  605. </p>
  606. <h3><a name="cap-b"></a><code>lpeg.Cb (key)</code></h3>
  607. <p>
  608. Creates a <em>back capture</em>.
  609. This pattern matches the empty string and
  610. produces the values produced by the <em>most recent</em>
  611. <a href="#cap-g">group capture</a> named <code>key</code>
  612. (where <code>key</code> can be any Lua value).
  613. </p>
  614. <p>
  615. <em>Most recent</em> means the last
  616. <em>complete</em>
  617. <em>outermost</em>
  618. group capture with the given key.
  619. A <em>Complete</em> capture means that the entire pattern
  620. corresponding to the capture has matched;
  621. in other words, the back capture is not nested inside the group.
  622. An <em>Outermost</em> capture means that the capture is not inside
  623. another complete capture that does not contain the back capture itself.
  624. </p>
  625. <p>
  626. In the same way that LPeg does not specify when it evaluates captures,
  627. it does not specify whether it reuses
  628. values previously produced by the group
  629. or re-evaluates them.
  630. </p>
  631. <h3><a name="cap-cc"></a><code>lpeg.Cc ([value, ...])</code></h3>
  632. <p>
  633. Creates a <em>constant capture</em>.
  634. This pattern matches the empty string and
  635. produces all given values as its captured values.
  636. </p>
  637. <h3><a name="cap-f"></a><code>lpeg.Cf (patt, func)</code></h3>
  638. <p>
  639. Creates a <em>fold capture</em>.
  640. This construction is deprecated;
  641. use an <a href="#cap-acc">accumulator pattern</a> instead.
  642. In general, a fold like
  643. <code>lpeg.Cf(p1 * p2^0, func)</code>
  644. can be translated to
  645. <code>(p1 * (p2 % func)^0)</code>.
  646. <h3><a name="cap-g"></a><code>lpeg.Cg (patt [, key])</code></h3>
  647. <p>
  648. Creates a <em>group capture</em>.
  649. It groups all values returned by <code>patt</code>
  650. into a single capture.
  651. The group may be anonymous (if no key is given)
  652. or named with the given key
  653. (which can be any non-nil Lua value).
  654. </p>
  655. <p>
  656. An anonymous group serves to join values from several captures into
  657. a single capture.
  658. A named group has a different behavior.
  659. In most situations, a named group returns no values at all.
  660. Its values are only relevant for a following
  661. <a href="#cap-b">back capture</a> or when used
  662. inside a <a href="#cap-t">table capture</a>.
  663. </p>
  664. <h3><a name="cap-p"></a><code>lpeg.Cp ()</code></h3>
  665. <p>
  666. Creates a <em>position capture</em>.
  667. It matches the empty string and
  668. captures the position in the subject where the match occurs.
  669. The captured value is a number.
  670. </p>
  671. <h3><a name="cap-s"></a><code>lpeg.Cs (patt)</code></h3>
  672. <p>
  673. Creates a <em>substitution capture</em>,
  674. which captures the substring of the subject that matches <code>patt</code>,
  675. with <em>substitutions</em>.
  676. For any capture inside <code>patt</code> with a value,
  677. the substring that matched the capture is replaced by the capture value
  678. (which should be a string).
  679. The final captured value is the string resulting from
  680. all replacements.
  681. </p>
  682. <h3><a name="cap-t"></a><code>lpeg.Ct (patt)</code></h3>
  683. <p>
  684. Creates a <em>table capture</em>.
  685. This capture returns a table with all values from all anonymous captures
  686. made by <code>patt</code> inside this table in successive integer keys,
  687. starting at 1.
  688. Moreover,
  689. for each named capture group created by <code>patt</code>,
  690. the first value of the group is put into the table
  691. with the group key as its key.
  692. The captured value is only the table.
  693. </p>
  694. <h3><a name="cap-string"></a><code>patt / string</code></h3>
  695. <p>
  696. Creates a <em>string capture</em>.
  697. It creates a capture string based on <code>string</code>.
  698. The captured value is a copy of <code>string</code>,
  699. except that the character <code>%</code> works as an escape character:
  700. any sequence in <code>string</code> of the form <code>%<em>n</em></code>,
  701. with <em>n</em> between 1 and 9,
  702. stands for the match of the <em>n</em>-th capture in <code>patt</code>.
  703. The sequence <code>%0</code> stands for the whole match.
  704. The sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
  705. </p>
  706. <h3><a name="cap-num"></a><code>patt / number</code></h3>
  707. <p>
  708. Creates a <em>numbered capture</em>.
  709. For a non-zero number,
  710. the captured value is the n-th value
  711. captured by <code>patt</code>.
  712. When <code>number</code> is zero,
  713. there are no captured values.
  714. </p>
  715. <h3><a name="cap-query"></a><code>patt / table</code></h3>
  716. <p>
  717. Creates a <em>query capture</em>.
  718. It indexes the given table using as key the first value captured by
  719. <code>patt</code>,
  720. or the whole match if <code>patt</code> produced no value.
  721. The value at that index is the final value of the capture.
  722. If the table does not have that key,
  723. there is no captured value.
  724. </p>
  725. <h3><a name="cap-func"></a><code>patt / function</code></h3>
  726. <p>
  727. Creates a <em>function capture</em>.
  728. It calls the given function passing all captures made by
  729. <code>patt</code> as arguments,
  730. or the whole match if <code>patt</code> made no capture.
  731. The values returned by the function
  732. are the final values of the capture.
  733. In particular,
  734. if <code>function</code> returns no value,
  735. there is no captured value.
  736. </p>
  737. <h3><a name="cap-acc"></a><code>patt % function</code></h3>
  738. <p>
  739. Creates an <em>accumulator capture</em>.
  740. This pattern behaves similarly to a
  741. <a href="#cap-func">function capture</a>,
  742. with the following differences:
  743. The last captured value before <code>patt</code>
  744. is added as a first argument to the call;
  745. the return of the function is adjusted to one single value;
  746. that value replaces the last captured value.
  747. Note that the capture itself produces no values;
  748. it only changes the value of its previous capture.
  749. </p>
  750. <p>
  751. As an example,
  752. let us consider the problem of adding a list of numbers.
  753. </p>
  754. <pre class="example">
  755. -- matches a numeral and captures its numerical value
  756. number = lpeg.R"09"^1 / tonumber
  757. -- auxiliary function to add two numbers
  758. function add (acc, newvalue) return acc + newvalue end
  759. -- matches a list of numbers, adding their values
  760. sum = number * ("," * number % add)^0
  761. -- example of use
  762. print(sum:match("10,30,43")) --&gt; 83
  763. </pre>
  764. <p>
  765. First, the initial <code>number</code> captures a number;
  766. that first capture will play the role of an accumulator.
  767. Then, each time the sequence <code>comma-number</code>
  768. matches inside the loop there is an accumulator capture:
  769. It calls <code>add</code> with the current value of the
  770. accumulator&mdash;which is the last captured value, created by the
  771. first <code>number</code>&mdash; and the value of the new number,
  772. and the result of the call (the sum of the two numbers)
  773. replaces the value of the accumulator.
  774. At the end of the match,
  775. the accumulator with all sums is the final value.
  776. </p>
  777. <p>
  778. As another example,
  779. consider the following code fragment:
  780. </p>
  781. <pre class="example">
  782. local name = lpeg.C(lpeg.R("az")^1)
  783. local p = name * (lpeg.P("^") % string.upper)^-1
  784. print(p:match("count")) --&gt; count
  785. print(p:match("count^")) --&gt; COUNT
  786. </pre>
  787. <p>
  788. In the match against <code>"count"</code>,
  789. as there is no <code>"^"</code>,
  790. the optional accumulator capture does not match;
  791. so, the match results in its sole capture, a name.
  792. In the match against <code>"count^"</code>,
  793. the accumulator capture matches,
  794. so the function <code>string.upper</code>
  795. is called with the previous captured value (created by <code>name</code>)
  796. plus the string <code>"^"</code>;
  797. the function ignores its second argument and returns the first argument
  798. changed to upper case;
  799. that value then becomes the first and only
  800. capture value created by the match.
  801. </p>
  802. <p>
  803. Due to the nature of this capture,
  804. you should avoid using it in places where it is not clear
  805. what is the "previous" capture,
  806. such as directly nested in a <a href="#cap-string">string capture</a>
  807. or a <a href="#cap-num">numbered capture</a>.
  808. (Note that these captures may not need to evaluate
  809. all their subcaptures to compute their results.)
  810. Moreover, due to implementation details,
  811. you should not use this capture directly nested in a
  812. <a href="#cap-s">substitution capture</a>.
  813. You should also avoid a direct nesting of this capture inside
  814. a <a href="#cap-f">folding capture</a> (deprecated),
  815. as the folding will try to fold each individual accumulator capture.
  816. A simple and effective way to avoid all these issues is
  817. to enclose the whole accumulation composition
  818. (including the capture that generates the initial value)
  819. into an anonymous <a href="#cap-g">group capture</a>.
  820. </p>
  821. <h3><a name="matchtime"></a><code>lpeg.Cmt(patt, function)</code></h3>
  822. <p>
  823. Creates a <em>match-time capture</em>.
  824. Unlike all other captures,
  825. this one is evaluated immediately when a match occurs
  826. (even if it is part of a larger pattern that fails later).
  827. It forces the immediate evaluation of all its nested captures
  828. and then calls <code>function</code>.
  829. </p>
  830. <p>
  831. The given function gets as arguments the entire subject,
  832. the current position (after the match of <code>patt</code>),
  833. plus any capture values produced by <code>patt</code>.
  834. </p>
  835. <p>
  836. The first value returned by <code>function</code>
  837. defines how the match happens.
  838. If the call returns a number,
  839. the match succeeds
  840. and the returned number becomes the new current position.
  841. (Assuming a subject <em>s</em> and current position <em>i</em>,
  842. the returned number must be in the range <em>[i, len(s) + 1]</em>.)
  843. If the call returns <b>true</b>,
  844. the match succeeds without consuming any input.
  845. (So, to return <b>true</b> is equivalent to return <em>i</em>.)
  846. If the call returns <b>false</b>, <b>nil</b>, or no value,
  847. the match fails.
  848. </p>
  849. <p>
  850. Any extra values returned by the function become the
  851. values produced by the capture.
  852. </p>
  853. <h2><a name="ex">Some Examples</a></h2>
  854. <h3>Using a Pattern</h3>
  855. <p>
  856. This example shows a very simple but complete program
  857. that builds and uses a pattern:
  858. </p>
  859. <pre class="example">
  860. local lpeg = require "lpeg"
  861. -- matches a word followed by end-of-string
  862. p = lpeg.R"az"^1 * -1
  863. print(p:match("hello")) --&gt; 6
  864. print(lpeg.match(p, "hello")) --&gt; 6
  865. print(p:match("1 hello")) --&gt; nil
  866. </pre>
  867. <p>
  868. The pattern is simply a sequence of one or more lower-case letters
  869. followed by the end of string (-1).
  870. The program calls <code>match</code> both as a method
  871. and as a function.
  872. In both sucessful cases,
  873. the match returns
  874. the index of the first character after the match,
  875. which is the string length plus one.
  876. </p>
  877. <h3>Name-value lists</h3>
  878. <p>
  879. This example parses a list of name-value pairs and returns a table
  880. with those pairs:
  881. </p>
  882. <pre class="example">
  883. lpeg.locale(lpeg) -- adds locale entries into 'lpeg' table
  884. local space = lpeg.space^0
  885. local name = lpeg.C(lpeg.alpha^1) * space
  886. local sep = lpeg.S(",;") * space
  887. local pair = name * "=" * space * name * sep^-1
  888. local list = lpeg.Ct("") * (pair % rawset)^0
  889. t = list:match("a=b, c = hi; next = pi")
  890. --&gt; { a = "b", c = "hi", next = "pi" }
  891. </pre>
  892. <p>
  893. Each pair has the format <code>name = name</code> followed by
  894. an optional separator (a comma or a semicolon).
  895. The <code>list</code> pattern then <em>folds</em> these captures.
  896. It starts with an empty table,
  897. created by a table capture matching an empty string;
  898. then for each a pair of names it applies <code>rawset</code>
  899. over the accumulator (the table) and the capture values (the pair of names).
  900. <code>rawset</code> returns the table itself,
  901. so the accumulator is always the table.
  902. </p>
  903. <h3>Splitting a string</h3>
  904. <p>
  905. The following code builds a pattern that
  906. splits a string using a given pattern
  907. <code>sep</code> as a separator:
  908. </p>
  909. <pre class="example">
  910. function split (s, sep)
  911. sep = lpeg.P(sep)
  912. local elem = lpeg.C((1 - sep)^0)
  913. local p = elem * (sep * elem)^0
  914. return lpeg.match(p, s)
  915. end
  916. </pre>
  917. <p>
  918. First the function ensures that <code>sep</code> is a proper pattern.
  919. The pattern <code>elem</code> is a repetition of zero of more
  920. arbitrary characters as long as there is not a match against
  921. the separator.
  922. It also captures its match.
  923. The pattern <code>p</code> matches a list of elements separated
  924. by <code>sep</code>.
  925. </p>
  926. <p>
  927. If the split results in too many values,
  928. it may overflow the maximum number of values
  929. that can be returned by a Lua function.
  930. To avoid this problem,
  931. we can collect these values in a table:
  932. </p>
  933. <pre class="example">
  934. function split (s, sep)
  935. sep = lpeg.P(sep)
  936. local elem = lpeg.C((1 - sep)^0)
  937. local p = lpeg.Ct(elem * (sep * elem)^0) -- make a table capture
  938. return lpeg.match(p, s)
  939. end
  940. </pre>
  941. <h3>Searching for a pattern</h3>
  942. <p>
  943. The primitive <code>match</code> works only in anchored mode.
  944. If we want to find a pattern anywhere in a string,
  945. we must write a pattern that matches anywhere.
  946. </p>
  947. <p>
  948. Because patterns are composable,
  949. we can write a function that,
  950. given any arbitrary pattern <code>p</code>,
  951. returns a new pattern that searches for <code>p</code>
  952. anywhere in a string.
  953. There are several ways to do the search.
  954. One way is like this:
  955. </p>
  956. <pre class="example">
  957. function anywhere (p)
  958. return lpeg.P{ p + 1 * lpeg.V(1) }
  959. end
  960. </pre>
  961. <p>
  962. This grammar has a straight reading:
  963. its sole rule matches <code>p</code> or skips one character and tries again.
  964. </p>
  965. <p>
  966. If we want to know where the pattern is in the string
  967. (instead of knowing only that it is there somewhere),
  968. we can add position captures to the pattern:
  969. </p>
  970. <pre class="example">
  971. local Cp = lpeg.Cp()
  972. function anywhere (p)
  973. return lpeg.P{ Cp * p * Cp + 1 * lpeg.V(1) }
  974. end
  975. print(anywhere("world"):match("hello world!")) --&gt; 7 12
  976. </pre>
  977. <p>
  978. Another option for the search is like this:
  979. </p>
  980. <pre class="example">
  981. local Cp = lpeg.Cp()
  982. function anywhere (p)
  983. return (1 - lpeg.P(p))^0 * Cp * p * Cp
  984. end
  985. </pre>
  986. <p>
  987. Again the pattern has a straight reading:
  988. it skips as many characters as possible while not matching <code>p</code>,
  989. and then matches <code>p</code> plus appropriate captures.
  990. </p>
  991. <p>
  992. If we want to look for a pattern only at word boundaries,
  993. we can use the following transformer:
  994. </p>
  995. <pre class="example">
  996. local t = lpeg.locale()
  997. function atwordboundary (p)
  998. return lpeg.P{
  999. [1] = p + t.alpha^0 * (1 - t.alpha)^1 * lpeg.V(1)
  1000. }
  1001. end
  1002. </pre>
  1003. <h3><a name="balanced"></a>Balanced parentheses</h3>
  1004. <p>
  1005. The following pattern matches only strings with balanced parentheses:
  1006. </p>
  1007. <pre class="example">
  1008. b = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
  1009. </pre>
  1010. <p>
  1011. Reading the first (and only) rule of the given grammar,
  1012. we have that a balanced string is
  1013. an open parenthesis,
  1014. followed by zero or more repetitions of either
  1015. a non-parenthesis character or
  1016. a balanced string (<code>lpeg.V(1)</code>),
  1017. followed by a closing parenthesis.
  1018. </p>
  1019. <h3>Global substitution</h3>
  1020. <p>
  1021. The next example does a job somewhat similar to <code>string.gsub</code>.
  1022. It receives a pattern and a replacement value,
  1023. and substitutes the replacement value for all occurrences of the pattern
  1024. in a given string:
  1025. </p>
  1026. <pre class="example">
  1027. function gsub (s, patt, repl)
  1028. patt = lpeg.P(patt)
  1029. patt = lpeg.Cs((patt / repl + 1)^0)
  1030. return lpeg.match(patt, s)
  1031. end
  1032. </pre>
  1033. <p>
  1034. As in <code>string.gsub</code>,
  1035. the replacement value can be a string,
  1036. a function, or a table.
  1037. </p>
  1038. <h3><a name="CSV"></a>Comma-Separated Values (CSV)</h3>
  1039. <p>
  1040. This example breaks a string into comma-separated values,
  1041. returning all fields:
  1042. </p>
  1043. <pre class="example">
  1044. local field = '"' * lpeg.Cs(((lpeg.P(1) - '"') + lpeg.P'""' / '"')^0) * '"' +
  1045. lpeg.C((1 - lpeg.S',\n"')^0)
  1046. local record = field * (',' * field)^0 * (lpeg.P'\n' + -1)
  1047. function csv (s)
  1048. return lpeg.match(record, s)
  1049. end
  1050. </pre>
  1051. <p>
  1052. A field is either a quoted field
  1053. (which may contain any character except an individual quote,
  1054. which may be written as two quotes that are replaced by one)
  1055. or an unquoted field
  1056. (which cannot contain commas, newlines, or quotes).
  1057. A record is a list of fields separated by commas,
  1058. ending with a newline or the string end (-1).
  1059. </p>
  1060. <p>
  1061. As it is,
  1062. the previous pattern returns each field as a separated result.
  1063. If we add a table capture in the definition of <code>record</code>,
  1064. the pattern will return instead a single table
  1065. containing all fields:
  1066. </p>
  1067. <pre>
  1068. local record = lpeg.Ct(field * (',' * field)^0) * (lpeg.P'\n' + -1)
  1069. </pre>
  1070. <h3>Lua's long strings</h3>
  1071. <p>
  1072. A long string in Lua starts with the pattern <code>[=*[</code>
  1073. and ends at the first occurrence of <code>]=*]</code> with
  1074. exactly the same number of equal signs.
  1075. If the opening brackets are followed by a newline,
  1076. this newline is discarded
  1077. (that is, it is not part of the string).
  1078. </p>
  1079. <p>
  1080. To match a long string in Lua,
  1081. the pattern must capture the first repetition of equal signs and then,
  1082. whenever it finds a candidate for closing the string,
  1083. check whether it has the same number of equal signs.
  1084. </p>
  1085. <pre class="example">
  1086. equals = lpeg.P"="^0
  1087. open = "[" * lpeg.Cg(equals, "init") * "[" * lpeg.P"\n"^-1
  1088. close = "]" * lpeg.C(equals) * "]"
  1089. closeeq = lpeg.Cmt(close * lpeg.Cb("init"), function (s, i, a, b) return a == b end)
  1090. string = open * lpeg.C((lpeg.P(1) - closeeq)^0) * close / 1
  1091. </pre>
  1092. <p>
  1093. The <code>open</code> pattern matches <code>[=*[</code>,
  1094. capturing the repetitions of equal signs in a group named <code>init</code>;
  1095. it also discharges an optional newline, if present.
  1096. The <code>close</code> pattern matches <code>]=*]</code>,
  1097. also capturing the repetitions of equal signs.
  1098. The <code>closeeq</code> pattern first matches <code>close</code>;
  1099. then it uses a back capture to recover the capture made
  1100. by the previous <code>open</code>,
  1101. which is named <code>init</code>;
  1102. finally it uses a match-time capture to check
  1103. whether both captures are equal.
  1104. The <code>string</code> pattern starts with an <code>open</code>,
  1105. then it goes as far as possible until matching <code>closeeq</code>,
  1106. and then matches the final <code>close</code>.
  1107. The final numbered capture simply discards
  1108. the capture made by <code>close</code>.
  1109. </p>
  1110. <h3>Arithmetic expressions</h3>
  1111. <p>
  1112. This example is a complete parser and evaluator for simple
  1113. arithmetic expressions.
  1114. We write it in two styles.
  1115. The first approach first builds a syntax tree and then
  1116. traverses this tree to compute the expression value:
  1117. </p>
  1118. <pre class="example">
  1119. -- Lexical Elements
  1120. local Space = lpeg.S(" \n\t")^0
  1121. local Number = lpeg.C(lpeg.P"-"^-1 * lpeg.R("09")^1) * Space
  1122. local TermOp = lpeg.C(lpeg.S("+-")) * Space
  1123. local FactorOp = lpeg.C(lpeg.S("*/")) * Space
  1124. local Open = "(" * Space
  1125. local Close = ")" * Space
  1126. -- Grammar
  1127. local Exp, Term, Factor = lpeg.V"Exp", lpeg.V"Term", lpeg.V"Factor"
  1128. G = lpeg.P{ Exp,
  1129. Exp = lpeg.Ct(Term * (TermOp * Term)^0);
  1130. Term = lpeg.Ct(Factor * (FactorOp * Factor)^0);
  1131. Factor = Number + Open * Exp * Close;
  1132. }
  1133. G = Space * G * -1
  1134. -- Evaluator
  1135. function eval (x)
  1136. if type(x) == "string" then
  1137. return tonumber(x)
  1138. else
  1139. local op1 = eval(x[1])
  1140. for i = 2, #x, 2 do
  1141. local op = x[i]
  1142. local op2 = eval(x[i + 1])
  1143. if (op == "+") then op1 = op1 + op2
  1144. elseif (op == "-") then op1 = op1 - op2
  1145. elseif (op == "*") then op1 = op1 * op2
  1146. elseif (op == "/") then op1 = op1 / op2
  1147. end
  1148. end
  1149. return op1
  1150. end
  1151. end
  1152. -- Parser/Evaluator
  1153. function evalExp (s)
  1154. local t = lpeg.match(G, s)
  1155. if not t then error("syntax error", 2) end
  1156. return eval(t)
  1157. end
  1158. -- small example
  1159. print(evalExp"3 + 5*9 / (1+1) - 12") --&gt; 13.5
  1160. </pre>
  1161. <p>
  1162. The second style computes the expression value on the fly,
  1163. without building the syntax tree.
  1164. The following grammar takes this approach.
  1165. (It assumes the same lexical elements as before.)
  1166. </p>
  1167. <pre class="example">
  1168. -- Auxiliary function
  1169. function eval (v1, op, v2)
  1170. if (op == "+") then return v1 + v2
  1171. elseif (op == "-") then return v1 - v2
  1172. elseif (op == "*") then return v1 * v2
  1173. elseif (op == "/") then return v1 / v2
  1174. end
  1175. end
  1176. -- Grammar
  1177. local V = lpeg.V
  1178. G = lpeg.P{ "Exp",
  1179. Exp = V"Term" * (TermOp * V"Term" % eval)^0;
  1180. Term = V"Factor" * (FactorOp * V"Factor" % eval)^0;
  1181. Factor = Number / tonumber + Open * V"Exp" * Close;
  1182. }
  1183. -- small example
  1184. print(lpeg.match(G, "3 + 5*9 / (1+1) - 12")) --&gt; 13.5
  1185. </pre>
  1186. <p>
  1187. Note the use of the accumulator capture.
  1188. To compute the value of an expression,
  1189. the accumulator starts with the value of the first term,
  1190. and then applies <code>eval</code> over
  1191. the accumulator, the operator,
  1192. and the new term for each repetition.
  1193. </p>
  1194. <h2><a name="download"></a>Download</h2>
  1195. <p>LPeg
  1196. <a href="//www.inf.puc-rio.br/~roberto/lpeg/lpeg-1.1.0.tar.gz">source code</a>.</p>
  1197. <p>
  1198. Probably, the easiest way to install LPeg is with
  1199. <a href="//luarocks.org/">LuaRocks</a>.
  1200. If you have LuaRocks installed,
  1201. the following command is all you need to install LPeg:
  1202. <pre>$ luarocks install lpeg</pre>
  1203. <h2><a name="license">License</a></h2>
  1204. <p>
  1205. Copyright &copy; 2007-2023 Lua.org, PUC-Rio.
  1206. </p>
  1207. <p>
  1208. Permission is hereby granted, free of charge,
  1209. to any person obtaining a copy of this software and
  1210. associated documentation files (the "Software"),
  1211. to deal in the Software without restriction,
  1212. including without limitation the rights to use,
  1213. copy, modify, merge, publish, distribute, sublicense,
  1214. and/or sell copies of the Software,
  1215. and to permit persons to whom the Software is
  1216. furnished to do so,
  1217. subject to the following conditions:
  1218. </p>
  1219. <p>
  1220. The above copyright notice and this permission notice
  1221. shall be included in all copies or substantial portions of the Software.
  1222. </p>
  1223. <p>
  1224. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  1225. EXPRESS OR IMPLIED,
  1226. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1227. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  1228. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1229. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  1230. TORT OR OTHERWISE, ARISING FROM,
  1231. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1232. THE SOFTWARE.
  1233. </p>
  1234. </div> <!-- id="content" -->
  1235. </div> <!-- id="main" -->
  1236. </div> <!-- id="container" -->
  1237. </body>
  1238. </html>