LPeg is a pattern-matching library for Lua,based onParsing Expression Grammars (PEGs).This text is a reference manual for the library.For those starting with LPeg,Mastering LPeg presents a good tutorial.For a more formal treatment of LPeg,as well as some discussion about its implementation,seeA Text Pattern-Matching Tool based on Parsing Expression Grammars.You may also be interested in mytalk about LPeggiven at the III Lua Workshop.
Following the Snobol tradition,LPeg defines patterns as first-class objects.That is, patterns are regular Lua values(represented by userdata).The library offers several functions to createand compose patterns.With the use of metamethods,several of these functions are provided as infix or prefixoperators.On the one hand,the result is usually much more verbose than the typicalencoding of patterns using the so calledregular expressions(which typically are not regular expressions in the formal sense).On the other hand,first-class patterns allow much better documentation(as it is easy to comment the code,to break complex definitions in smaller parts, etc.)and are extensible,as we can define new functions to create and compose patterns.
For a quick glance of the library,the following table summarizes its basic operationsfor creating patterns:
| Operator | Description |
lpeg.P(string) | Matchesstring literally |
lpeg.P(n) | Matches exactlyn characters |
lpeg.S(string) | Matches any character instring (Set) |
lpeg.R("xy") | Matches any character betweenx andy (Range) |
lpeg.utfR(cp1, cp2) | Matches an UTF-8 code point betweencp1 andcp2 |
patt^n | Matches at leastn repetitions ofpatt |
patt^-n | Matches at mostn repetitions ofpatt |
patt1 * patt2 | Matchespatt1 followed bypatt2 |
patt1 + patt2 | Matchespatt1 orpatt2 (ordered choice) |
patt1 - patt2 | Matchespatt1 ifpatt2 does not match |
-patt | Equivalent to("" - patt) |
#patt | Matchespatt but consumes no input |
lpeg.B(patt) | Matchespatt behind the current position, consuming no input |
As a very simple example,lpeg.R("09")^1 creates a pattern thatmatches a non-empty sequence of digits.As a not so simple example,-lpeg.P(1)(which can be written aslpeg.P(-1),or simply-1 for operations expecting a pattern)matches an empty string only if it cannot match a single character;so, it succeeds only at the end of the subject.
LPeg also offers there module,which implements patterns following a regular-expression style(e.g.,[09]+).(This module is 270 lines of Lua code,and of course it uses LPeg to parse regular expressions andtranslate them to regular LPeg patterns.)
lpeg.match (pattern, subject [, init])The matching function.It attempts to match the given pattern against the subject string.If the match succeeds,returns the index in the subject of the first character after the match,or thecaptured values(if the pattern captured any value).
An optional numeric argumentinit makes the matchstart at that position in the subject string.As in the Lua standard libraries,a negative value counts from the end.
Unlike typical pattern-matching functions,match works only inanchored mode;that is, it tries to match the pattern with a prefix ofthe given subject string (at positioninit),not with an arbitrary substring of the subject.So, if we want to find a pattern anywhere in a string,we must either write a loop in Lua or write a pattern thatmatches anywhere.This second approach is easy and quite efficient;seeexamples.
lpeg.type (value)If the given value is a pattern,returns the string"pattern".Otherwise returns nil.
lpeg.versionA string (not a function) with the running version of LPeg.
lpeg.setmaxstack (max)Sets a limit for the size of the backtrack stack used by LPeg totrack calls and choices.(The default limit is 400.)Most well-written patterns need little backtrack levels andtherefore you seldom need to change this limit;before changing it you should try to rewrite yourpattern to avoid the need for extra space.Nevertheless, a few useful patterns may overflow.Also, with recursive grammars,subjects with deep recursion may also need larger limits.
The following operations build patterns.All operations that expect a pattern as an argumentmay receive also strings, tables, numbers, booleans, or functions,which are translated to patterns according tothe rules of functionlpeg.P.
lpeg.P (value)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 the string literally.
If the argument is a non-negative numbern,the result is a pattern that matches exactlyn characters.
If the argument is a negative number-n,the result is a pattern thatsucceeds only if the input string has less thann characters left:lpeg.P(-n)is equivalent to-lpeg.P(n)(see theunary minus operation).
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.
If the argument is a table,it is interpreted as a grammar(seeGrammars).
If the argument is a function,returns a pattern equivalent to amatch-time capture over the empty string.
lpeg.B(patt)Returns a pattern thatmatches only if the input string at the current positionis preceded bypatt.Patternpatt must match only stringswith some fixed length,and it cannot contain captures.
Like theand predicate,this pattern never consumes any input,independently of success or failure.
lpeg.R ({range})Returns a pattern that matches any single characterbelonging to one of the givenranges.Eachrange is a stringxy of length 2,representing all characters with codebetween the codes ofx andy(both inclusive).
As an example, the patternlpeg.R("09") matches any digit,andlpeg.R("az", "AZ") matches any ASCII letter.
lpeg.S (string)Returns a pattern that matches any single character thatappears in the given string.(TheS stands forSet.)
As an example, the patternlpeg.S("+-*/") matches any arithmetic operator.
Note that, ifs is a character(that is, a string of length 1),thenlpeg.P(s) is equivalent tolpeg.S(s)which is equivalent tolpeg.R(s..s).Note also that bothlpeg.S("") andlpeg.R()are patterns that always fail.
lpeg.utfR (cp1, cp2)Returns a pattern that matches a valid UTF-8 byte sequencerepresenting a code point in the range[cp1, cp2].The range is limited by the natural Unicode limit of 0x10FFFF,but may include surrogates.
lpeg.V (v)This operation creates a non-terminal (avariable)for a grammar.The created non-terminal refers to the rule indexed byvin the enclosing grammar.(SeeGrammars for details.)
lpeg.locale ([table])Returns a table with patterns for matching some character classesaccording to the current locale.The table has fields namedalnum,alpha,cntrl,digit,graph,lower,print,punct,space,upper, andxdigit,each one containing a correspondent pattern.Each pattern matches any single character that belongs to its class.
If called with an argumenttable,then it creates those fields inside the given table andreturns that table.
#pattReturns a pattern thatmatches only if the input string matchespatt,but without consuming any input,independently of success or failure.(This pattern is called anand predicateand it is equivalent to&patt in the original PEG notation.)
This pattern never produces any capture.
-pattReturns a pattern thatmatches only if the input string does not matchpatt.It does not consume any input,independently of success or failure.(This pattern is equivalent to!patt in the original PEG notation.)
As an example, the pattern-lpeg.P(1) matches only the end of string.
This pattern never produces any captures,because eitherpatt failsor-patt fails.(A failing pattern never produces captures.)
patt1 + patt2Returns a pattern equivalent to anordered choiceofpatt1 andpatt2.(This is denoted bypatt1 / patt2 in the original PEG notation,not to be confused with the/ operation in LPeg.)It matches eitherpatt1 orpatt2,with no backtracking once one of them succeeds.The identity element for this operation is the patternlpeg.P(false),which always fails.
If bothpatt1 andpatt2 arecharacter sets,this operation is equivalent to set union.
lower = lpeg.R("az")upper = lpeg.R("AZ")letter = lower + upperpatt1 - patt2Returns a pattern equivalent to!patt2 patt1in the origial PEG notation.This pattern asserts that the input does not matchpatt2 and then matchespatt1.
When successful,this pattern produces all captures frompatt1.It never produces any capture frompatt2(as eitherpatt2 fails orpatt1 - patt2 fails).
If bothpatt1 andpatt2 arecharacter sets,this operation is equivalent to set difference.Note that-patt is equivalent to"" - patt(or0 - patt).Ifpatt is a character set,1 - patt is its complement.
patt1 * patt2Returns a pattern that matchespatt1and then matchespatt2,starting wherepatt1 finished.The identity element for this operation is thepatternlpeg.P(true),which always succeeds.
(LPeg uses the* operator[instead of the more obvious..]both because it hasthe right priority and because in formal languages it iscommon to use a dot for denoting concatenation.)
patt^nIfn is nonnegative,this pattern isequivalent topattn patt*:It matchesn or more occurrences ofpatt.
Otherwise, whenn is negative,this pattern is equivalent to(patt?)-n:It matches at most|n|occurrences ofpatt.
In particular,patt^0 is equivalent topatt*,patt^1 is equivalent topatt+,andpatt^-1 is equivalent topatt?in the original PEG notation.
In all cases,the resulting pattern is greedy with no backtracking(also called apossessive repetition).That is, it matches only the longest possible sequenceof matches forpatt.
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 ofrecursive patterns.For recursive patterns,we need real grammars.
LPeg represents grammars with tables,where each entry is a rule.
The calllpeg.V(v)creates a pattern that represents the nonterminal(orvariable) with indexv in a grammar.Because the grammar still does not exist whenthis function is evaluated,the result is anopen reference to the respective rule.
A table isfixed when it is converted to a pattern(either by callinglpeg.P or by using it wherein apattern is expected).Then every open reference created bylpeg.V(v)is corrected to refer to the rule indexed byv in the table.
When a table is fixed,the result is a pattern that matches itsinitial 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 thathave 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",} * -1It is equivalent to the following grammar in standard PEG notation:
S<- 'a' B / 'b' A / '' A<- 'a' S / 'b' A A B<- 'b' S / 'a' B B
Acapture is a pattern that produces values(the so calledsemantic information)according to what it matches.LPeg offers several kinds of captures,which produces values based on matches and combine these values toproduce new values.Each capture may produce zero or more values.
The following table summarizes the basic captures:
| Operation | What it Produces |
lpeg.C(patt) | the match forpatt plus all captures made bypatt |
lpeg.Carg(n) | the value of the nth extra argument tolpeg.match (matches the empty string) |
lpeg.Cb(key) | the values produced by the previous group capture namedkey (matches the empty string) |
lpeg.Cc(values) | the given values (matches the empty string) |
lpeg.Cf(patt, func) | folding capture (deprecated) |
lpeg.Cg(patt [, key]) | the values produced bypatt, optionally tagged withkey |
lpeg.Cp() | the current position (matches the empty string) |
lpeg.Cs(patt) | the match forpatt with the values from nested captures replacing their matches |
lpeg.Ct(patt) | a table with all captures frompatt |
patt / string | string, with some marks replaced by captures ofpatt |
patt / number | the n-th value captured bypatt,or no value whennumber is zero. |
patt / table | table[c], wherec is the (first) capture ofpatt |
patt / function | the returns offunction applied to the captures ofpatt |
patt % function | produces no value; itaccummulates the captures frompatt into the previous capture throughfunction |
lpeg.Cmt(patt, function) | the returns offunction applied to the captures ofpatt; the application is done at match time |
A capture pattern produces its values only when it succeeds.For instance,the patternlpeg.C(lpeg.P"a"^-1)produces the empty string when there is no"a"(because the pattern"a"? succeeds),while the patternlpeg.C("a")^-1does not produce any value when there is no"a"(because the pattern"a" fails).A pattern inside a loop or inside a recursive structureproduces values for each match.
Usually,LPeg does not specify when, if, or how many times it evaluates its captures.Therefore, captures should avoid side effects.As an example,LPeg may or may not callfunc in the patternlpeg.P"a" / func / 0,given that the"division" by 0instructs LPeg to throw away theresults from the pattern.Similarly, a capture nested inside anamed groupmay be evaluated only when that group is referred in aback capture;if there are multiple back captures,the group may be evaluated multiple times.
Moreover,captures cannot affect the way a pattern matches a subject.The only exception to this rule is theso-calledmatch-time capture.When a match-time capture matches,it forces the immediate evaluation of all its nested capturesand then calls its corresponding function,which defines whether the match succeeds and alsowhat values are produced.
lpeg.C (patt)Creates asimple capture,which captures the substring of the subject that matchespatt.The captured value is a string.Ifpatt has other captures,their values are returned after this one.
lpeg.Carg (n)Creates anargument capture.This pattern matches the empty string andproduces the value given as the nth extraargument given in the call tolpeg.match.
lpeg.Cb (key)Creates aback capture.This pattern matches the empty string andproduces the values produced by themost recentgroup capture namedkey(wherekey can be any Lua value).
Most recent means the lastcompleteoutermostgroup capture with the given key.AComplete capture means that the entire patterncorresponding to the capture has matched;in other words, the back capture is not nested inside the group.AnOutermost capture means that the capture is not insideanother complete capture that does not contain the back capture itself.
In the same way that LPeg does not specify when it evaluates captures,it does not specify whether it reusesvalues previously produced by the groupor re-evaluates them.
lpeg.Cc ([value, ...])Creates aconstant capture.This pattern matches the empty string andproduces all given values as its captured values.
lpeg.Cf (patt, func)Creates afold capture.This construction is deprecated;use anaccumulator pattern instead.In general, a fold likelpeg.Cf(p1 * p2^0, func)can be translated to(p1 * (p2 % func)^0).
lpeg.Cg (patt [, key])Creates agroup capture.It groups all values returned bypattinto a single capture.The group may be anonymous (if no key is given)or named with the given key(which can be any non-nil Lua value).
An anonymous group serves to join values from several captures intoa 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 followingback capture or when usedinside atable capture.
lpeg.Cp ()Creates aposition capture.It matches the empty string andcaptures the position in the subject where the match occurs.The captured value is a number.
lpeg.Cs (patt)Creates asubstitution capture,which captures the substring of the subject that matchespatt,withsubstitutions.For any capture insidepatt with a value,the substring that matched the capture is replaced by the capture value(which should be a string).The final captured value is the string resulting fromall replacements.
lpeg.Ct (patt)Creates atable capture.This capture returns a table with all values from all anonymous capturesmade bypatt inside this table in successive integer keys,starting at 1.Moreover,for each named capture group created bypatt,the first value of the group is put into the tablewith the group key as its key.The captured value is only the table.
patt / stringCreates astring capture.It creates a capture string based onstring.The captured value is a copy ofstring,except that the character% works as an escape character:any sequence instring of the form%n,withn between 1 and 9,stands for the match of then-th capture inpatt.The sequence%0 stands for the whole match.The sequence%% stands for a single %.
patt / numberCreates anumbered capture.For a non-zero number,the captured value is the n-th valuecaptured bypatt. Whennumber is zero,there are no captured values.
patt / tableCreates aquery capture.It indexes the given table using as key the first value captured bypatt,or the whole match ifpatt produced no value.The value at that index is the final value of the capture.If the table does not have that key,there is no captured value.
patt / functionCreates afunction capture.It calls the given function passing all captures made bypatt as arguments,or the whole match ifpatt made no capture.The values returned by the functionare the final values of the capture.In particular,iffunction returns no value,there is no captured value.
patt % functionCreates anaccumulator capture.This pattern behaves similarly to afunction capture,with the following differences:The last captured value beforepattis added as a first argument to the call;the return of the function is adjusted to one single value;that value replaces the last captured value.Note that the capture itself produces no values;it only changes the value of its previous capture.
As an example,let us consider the problem of adding a list of numbers.
-- matches a numeral and captures its numerical valuenumber = lpeg.R"09"^1 / tonumber-- auxiliary function to add two numbersfunction add (acc, newvalue) return acc + newvalue end-- matches a list of numbers, adding their valuessum = number * ("," * number % add)^0-- example of useprint(sum:match("10,30,43")) --> 83First, the initialnumber captures a number;that first capture will play the role of an accumulator.Then, each time the sequencecomma-numbermatches inside the loop there is an accumulator capture:It callsadd with the current value of theaccumulator—which is the last captured value, created by thefirstnumber— and the value of the new number,and the result of the call (the sum of the two numbers)replaces the value of the accumulator.At the end of the match,the accumulator with all sums is the final value.
As another example,consider the following code fragment:
local name = lpeg.C(lpeg.R("az")^1)local p = name * (lpeg.P("^") % string.upper)^-1print(p:match("count")) --> countprint(p:match("count^")) --> COUNTIn the match against"count",as there is no"^",the optional accumulator capture does not match;so, the match results in its sole capture, a name.In the match against"count^",the accumulator capture matches,so the functionstring.upperis called with the previous captured value (created byname)plus the string"^";the function ignores its second argument and returns the first argumentchanged to upper case;that value then becomes the first and onlycapture value created by the match.
Due to the nature of this capture,you should avoid using it in places where it is not clearwhat is the "previous" capture,such as directly nested in astring captureor anumbered capture.(Note that these captures may not need to evaluateall their subcaptures to compute their results.)Moreover, due to implementation details,you should not use this capture directly nested in asubstitution capture.You should also avoid a direct nesting of this capture insideafolding capture (deprecated),as the folding will try to fold each individual accumulator capture.A simple and effective way to avoid all these issues isto enclose the whole accumulation composition(including the capture that generates the initial value)into an anonymousgroup capture.
lpeg.Cmt(patt, function)Creates amatch-time capture.Unlike all other captures,this one is evaluated immediately when a match occurs(even if it is part of a larger pattern that fails later).It forces the immediate evaluation of all its nested capturesand then callsfunction.
The given function gets as arguments the entire subject,the current position (after the match ofpatt),plus any capture values produced bypatt.
The first value returned byfunctiondefines how the match happens.If the call returns a number,the match succeedsand the returned number becomes the new current position.(Assuming a subjects and current positioni,the returned number must be in the range[i, len(s) + 1].)If the call returnstrue,the match succeeds without consuming any input.(So, to returntrue is equivalent to returni.)If the call returnsfalse,nil, or no value,the match fails.
Any extra values returned by the function become thevalues produced by the capture.
This example shows a very simple but complete programthat builds and uses a pattern:
local lpeg = require "lpeg"-- matches a word followed by end-of-stringp = lpeg.R"az"^1 * -1print(p:match("hello")) --> 6print(lpeg.match(p, "hello")) --> 6print(p:match("1 hello")) --> nilThe pattern is simply a sequence of one or more lower-case lettersfollowed by the end of string (-1).The program callsmatch both as a methodand as a function.In both sucessful cases,the match returns the index of the first character after the match,which is the string length plus one.
This example parses a list of name-value pairs and returns a tablewith those pairs:
lpeg.locale(lpeg) -- adds locale entries into 'lpeg' tablelocal space = lpeg.space^0local name = lpeg.C(lpeg.alpha^1) * spacelocal sep = lpeg.S(",;") * spacelocal pair = name * "=" * space * name * sep^-1local list = lpeg.Ct("") * (pair % rawset)^0t = list:match("a=b, c = hi; next = pi") --> { a = "b", c = "hi", next = "pi" }Each pair has the formatname = name followed byan optional separator (a comma or a semicolon).Thelist pattern thenfolds these captures.It starts with an empty table,created by a table capture matching an empty string;then for each a pair of names it appliesrawsetover the accumulator (the table) and the capture values (the pair of names).rawset returns the table itself,so the accumulator is always the table.
The following code builds a pattern thatsplits a string using a given patternsep as a separator:
function split (s, sep) sep = lpeg.P(sep) local elem = lpeg.C((1 - sep)^0) local p = elem * (sep * elem)^0 return lpeg.match(p, s)end
First the function ensures thatsep is a proper pattern.The patternelem is a repetition of zero of morearbitrary characters as long as there is not a match againstthe separator.It also captures its match.The patternp matches a list of elements separatedbysep.
If the split results in too many values,it may overflow the maximum number of valuesthat can be returned by a Lua function.To avoid this problem,we can collect these values in a table:
function split (s, sep) sep = lpeg.P(sep) local elem = lpeg.C((1 - sep)^0) local p = lpeg.Ct(elem * (sep * elem)^0) -- make a table capture return lpeg.match(p, s)end
The primitivematch works only in anchored mode.If we want to find a pattern anywhere in a string,we must write a pattern that matches anywhere.
Because patterns are composable,we can write a function that,given any arbitrary patternp,returns a new pattern that searches forpanywhere in a string.There are several ways to do the search.One way is like this:
function anywhere (p) return lpeg.P{ p + 1 * lpeg.V(1) }endThis grammar has a straight reading:its sole rule matchesp or skips one character and tries again.
If we want to know where the pattern is in the string(instead of knowing only that it is there somewhere),we can add position captures to the pattern:
local Cp = lpeg.Cp()function anywhere (p) return lpeg.P{ Cp * p * Cp + 1 * lpeg.V(1) }endprint(anywhere("world"):match("hello world!")) --> 7 12Another option for the search is like this:
local Cp = lpeg.Cp()function anywhere (p) return (1 - lpeg.P(p))^0 * Cp * p * Cpend
Again the pattern has a straight reading:it skips as many characters as possible while not matchingp,and then matchesp plus appropriate captures.
If we want to look for a pattern only at word boundaries,we can use the following transformer:
local t = lpeg.locale()function atwordboundary (p) return lpeg.P{ [1] = p + t.alpha^0 * (1 - t.alpha)^1 * lpeg.V(1) }endThe following pattern matches only strings with balanced parentheses:
b = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }Reading the first (and only) rule of the given grammar,we have that a balanced string isan open parenthesis,followed by zero or more repetitions of eithera non-parenthesis character ora balanced string (lpeg.V(1)),followed by a closing parenthesis.
The next example does a job somewhat similar tostring.gsub.It receives a pattern and a replacement value,and substitutes the replacement value for all occurrences of the patternin a given string:
function gsub (s, patt, repl) patt = lpeg.P(patt) patt = lpeg.Cs((patt / repl + 1)^0) return lpeg.match(patt, s)end
As instring.gsub,the replacement value can be a string,a function, or a table.
This example breaks a string into comma-separated values,returning all fields:
local field = '"' * lpeg.Cs(((lpeg.P(1) - '"') + lpeg.P'""' / '"')^0) * '"' + lpeg.C((1 - lpeg.S',\n"')^0)local record = field * (',' * field)^0 * (lpeg.P'\n' + -1)function csv (s) return lpeg.match(record, s)endA field is either a quoted field(which may contain any character except an individual quote,which may be written as two quotes that are replaced by one)or an unquoted field(which cannot contain commas, newlines, or quotes).A record is a list of fields separated by commas,ending with a newline or the string end (-1).
As it is,the previous pattern returns each field as a separated result.If we add a table capture in the definition ofrecord,the pattern will return instead a single tablecontaining all fields:
local record = lpeg.Ct(field * (',' * field)^0) * (lpeg.P'\n' + -1)A long string in Lua starts with the pattern[=*[and ends at the first occurrence of]=*] withexactly the same number of equal signs.If the opening brackets are followed by a newline,this newline is discarded(that is, it is not part of the string).
To match a long string in Lua,the pattern must capture the first repetition of equal signs and then,whenever it finds a candidate for closing the string,check whether it has the same number of equal signs.
equals = lpeg.P"="^0open = "[" * lpeg.Cg(equals, "init") * "[" * lpeg.P"\n"^-1close = "]" * lpeg.C(equals) * "]"closeeq = lpeg.Cmt(close * lpeg.Cb("init"), function (s, i, a, b) return a == b end)string = open * lpeg.C((lpeg.P(1) - closeeq)^0) * close / 1Theopen pattern matches[=*[,capturing the repetitions of equal signs in a group namedinit;it also discharges an optional newline, if present.Theclose pattern matches]=*],also capturing the repetitions of equal signs.Thecloseeq pattern first matchesclose;then it uses a back capture to recover the capture madeby the previousopen,which is namedinit;finally it uses a match-time capture to checkwhether both captures are equal.Thestring pattern starts with anopen,then it goes as far as possible until matchingcloseeq,and then matches the finalclose.The final numbered capture simply discardsthe capture made byclose.
This example is a complete parser and evaluator for simplearithmetic expressions.We write it in two styles.The first approach first builds a syntax tree and thentraverses this tree to compute the expression value:
-- Lexical Elementslocal Space = lpeg.S(" \n\t")^0local Number = lpeg.C(lpeg.P"-"^-1 * lpeg.R("09")^1) * Spacelocal TermOp = lpeg.C(lpeg.S("+-")) * Spacelocal FactorOp = lpeg.C(lpeg.S("*/")) * Spacelocal Open = "(" * Spacelocal Close = ")" * Space-- Grammarlocal Exp, Term, Factor = lpeg.V"Exp", lpeg.V"Term", lpeg.V"Factor"G = lpeg.P{ Exp, Exp = lpeg.Ct(Term * (TermOp * Term)^0); Term = lpeg.Ct(Factor * (FactorOp * Factor)^0); Factor = Number + Open * Exp * Close;}G = Space * G * -1-- Evaluatorfunction eval (x) if type(x) == "string" then return tonumber(x) else local op1 = eval(x[1]) for i = 2, #x, 2 do local op = x[i] local op2 = eval(x[i + 1]) if (op == "+") then op1 = op1 + op2 elseif (op == "-") then op1 = op1 - op2 elseif (op == "*") then op1 = op1 * op2 elseif (op == "/") then op1 = op1 / op2 end end return op1 endend-- Parser/Evaluatorfunction evalExp (s) local t = lpeg.match(G, s) if not t then error("syntax error", 2) end return eval(t)end-- small exampleprint(evalExp"3 + 5*9 / (1+1) - 12") --> 13.5The second style computes the expression value on the fly,without building the syntax tree.The following grammar takes this approach.(It assumes the same lexical elements as before.)
-- Auxiliary functionfunction eval (v1, op, v2) if (op == "+") then return v1 + v2 elseif (op == "-") then return v1 - v2 elseif (op == "*") then return v1 * v2 elseif (op == "/") then return v1 / v2 endend-- Grammarlocal V = lpeg.VG = lpeg.P{ "Exp", Exp = V"Term" * (TermOp * V"Term" % eval)^0; Term = V"Factor" * (FactorOp * V"Factor" % eval)^0; Factor = Number / tonumber + Open * V"Exp" * Close;}-- small exampleprint(lpeg.match(G, "3 + 5*9 / (1+1) - 12")) --> 13.5Note the use of the accumulator capture.To compute the value of an expression,the accumulator starts with the value of the first term,and then applieseval overthe accumulator, the operator,and the new term for each repetition.
LPegsource code.
Probably, the easiest way to install LPeg is withLuaRocks.If you have LuaRocks installed,the following command is all you need to install LPeg:
$ luarocks install lpeg
Copyright © 2007-2023 Lua.org, PUC-Rio.
Permission is hereby granted, free of charge,to any person obtaining a copy of this software andassociated documentation files (the "Software"),to deal in the Software without restriction,including without limitation the rights to use,copy, modify, merge, publish, distribute, sublicense,and/or sell copies of the Software,and to permit persons to whom the Software isfurnished to do so,subject to the following conditions:
The above copyright notice and this permission noticeshall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.