lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello,
I'm a very beginner in Lpeg and for my project, I started with arithmetic expressions evaluator on http://www.inf.puc-rio.br/~roberto/lpeg/

I don't understand the "Cf" behavior (code below).
Without Cf, I get what I want. With Cf not (see my comments in Grammar section).
How can I have the same result with Cf ?
Thank's a lot


local lpeg = require "lpeg"
match=lpeg.match
local C, P, R, S, V = lpeg.C, lpeg.P, lpeg.R, lpeg.S, lpeg.V
local Carg, Cc, Cp, Ct, Cs, Cg, Cf = lpeg.Carg, lpeg.Cc, lpeg.Cp, lpeg.Ct, lpeg.Cs, lpeg.Cg, lpeg.Cf
local guillemet=P('"')
local Separateur=S(',;')
local caractere=C(R'09'+R'az')^1-guillemet

-- Lexical Elements
local Space = S(" \n\t")^0
--local Number = C(S"+-"^-1 * R("09")^1) * Space
local Number = C(R("09")^1) * Space
local TermOp = C(S("+-")) * Space
local FactorOp = C(S("*/")) * Space
local Open = "(" * Space
local Close = ")" * Space

function parenthese(_expression_)
    return 'par{' .. _expression_ .. '}'
end

-- Grammar
local Exp, Term, Factor, Formule = V"Exp", V"Term", V"Factor", V"Formule"
local Grammaire = P { V'Exp',
  Exp = Term * Cg(TermOp * Term)^0,
  Term = Formule * Cg(FactorOp * Formule)^0+Cc('(')*TermOp*Formule*Cc(')')*Cg(FactorOp * Formule)^0,
  -- the following line works as expected : 1    +    par{    5    +    4    }
  Parentheses=Open*Cc('par{')*Exp*Cc('}')*Close,
  -- the following line doesn't work as expected : 1    +    par{5}
  -- Parentheses=Open*Cf(Exp,parenthese)*Close,
  texte = Cc('text{')*guillemet*C((1-guillemet)^0)*guillemet*Cc('}'),
  sans_texte=(Number^1+caractere^1),
  Formule=V'texte'+V'sans_texte'+V'Parentheses'
}

print(match(Grammaire,'1+(5+4)'))