lua-users home
lua-l archive

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


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

Ah ha. I didn't read your exact use case enough.
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).