• Subject: Re: PegDebug: trace debugger for LPeg
• From: Daurnimator <quae@...>
• Date: Tue, 23 Sep 2014 23:37:09 -0400

On 23 September 2014 22:04, Paul K wrote:
The fold function is not even called as there is only one capture.

When using lpeg.Cf, the accumulator can only be a single value/capture.

I slightly modified the example to add print("folding"...). If I
comment out the function capture, everything works; if it's
uncommented, then the fold function is not called. Am I missing
something?

The trick I alluded to was that the folding function will be called with all captures as arguments:

local lpeg = require('lpeg')
local grammar = { "Sum";
Number = lpeg.R"09"^1 / tonumber;
List = lpeg.V("Number") * ("," * lpeg.V("Number"))^0
/ function(...) print("S",select('#', ...)) return ... end
;
Sum = lpeg.Cf(lpeg.Cc(0)*lpeg.V("List"),
function(acc, newvalue, ...) print("folding", acc, newvalue, ...)
return newvalue and acc + newvalue end);
}
print(lpeg.match(lpeg.P(grammar),"10,30,43"))

Gives:

S       3
folding 0       10      30      43
10

While:
local lpeg = require('lpeg')
local grammar = { "Sum";
Number = lpeg.R"09"^1 / tonumber;
List = lpeg.V("Number") * ("," * lpeg.V("Number"))^0  ;
Sum = lpeg.Cf(lpeg.Cc(0)*lpeg.V("List"),
function(acc, newvalue, ...) print("folding", acc, newvalue, ...)
return newvalue and acc + newvalue end);
}
print(lpeg.match(lpeg.P(grammar),"10,30,43"))

Gives:

folding 0       10
folding 10      30
folding 40      43
83

The identity function in this situation acts like a grouping capture (lpeg.Cg).