lua-users home
lua-l archive

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


It was thus said that the Great Sean Conner once stated:
> It was thus said that the Great joy mondal once stated:
> > I tried using lpeg.Cf recursively and its quite convoluted.
> > 
> > For parsing thing like this:
> > 
> > [[[]]]
> 
>   What, exactly are you trying to parse there?  Something like:
> 
> 	[ 1 2 3 [ 4 5 6 [ 7 8 9 ] 10 11 ] 12 13 ] --?
> 
> > Its quite a bit easier with Cmt since I can create an empty table ( state )
> > at the start of the loop. with Cf you are not sure if you at the
> > start,middle or end of the loop.
> 
>   I rarely use lpeg.Cf() to fold captures into a table.  I'd rather use
> lpeg.Ct() with a capture pattern inside:
> 
> 	list = lpeg.P"[" * lpeg.Ct((SPACE * C(number))^0) * lpeg.P"]"
> 
> If it's recursive, then an LPEG grammar would be appropriate:
> 
> 	list = lpeg.P {
> 		'list',
> 		list = lpeg.P'[' * lpeg.Ct(lpeg.V"data") * lpeg.P']',
> 		data = SPACE * C(number)
>                      + lpeg.V"list"
> 	}
> 
> This would be enough to parse the example I'm asking about (given an
> appropriate definition for SPACE and number).

  I just reread your message, and perhaps I should present this definition
of list:

	list = lpeg.P {
		'list',
		list = lpeg.P'[' 
		     * lpeg.Cf(lpeg.Ct"" * lpeg.V"data"^0,function(a,b) table.insert(a,b) return a end)
		     * lpeg.P']',
		data = SPACE * C(number)
		     + lpeg.V"list"
	}

This uses lpeg.Cf() recursively (it also uses lpeg.Ct(), but only to
generate the table (generated by matching the empty string) used to
accumulate the results.  As you can see, it's a bit longer than just using
lpeg.Ct() around a pattern.

  -spc