[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Transform (cond ? then : else) to ifthenelse(cond, then, else) with lpeg
- From: William Ahern <william@...>
- Date: Mon, 20 Feb 2012 12:21:52 -0800
On Mon, Feb 20, 2012 at 06:21:17PM +0100, Christophe Jorssen wrote:
> Hello all,
>
> I'm trying to convert a string like
>
> 'a?(b?c:d):e'
>
> to another string
>
> 'ifthenelse(a,ifthenelse(b,c,d),e)'
>
> using the lpeg lua parser. I'm slowly learning how to use lpeg but I
> still can't find a suitable solution to do this with capture
> substitutions. Any ideas?
local lpeg = require("lpeg")
lpeg.locale(lpeg)
local function tr(a, b, c)
if not b then
return a
else
return string.format("ifthenelse(%s,%s,%s)", a, b, c)
end
end
local var = lpeg.C(lpeg.alpha * (lpeg.alnum^0))
local E, G = lpeg.V"E", lpeg.V"G"
local grammar = lpeg.P{ "E",
E = ((var + G) * (lpeg.P"?" * E * lpeg.P":" * E)^-1) / tr,
G = lpeg.P"(" * E * lpeg.P")",
}
print(lpeg.match(grammar, "a?(b?c:d):e"))