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 Dirk Laurie once stated:
> 2015-08-16 17:16 GMT+02:00 Soni L. <fakedme@gmail.com>:
> 
> > It should be constructed as `pattern | {cases}`.
> >
> > Here's how it works:
> >
> > You match the pattern `pattern`. You use the result of that match to index
> > into `{cases}`. `{cases}` is a key-value map from strings (match results) to
> > patterns. If the key doesn't exist, the match fails, otherwise we attempt to
> > match the indexed pattern (match the value we got from `{cases}`).
> >
> > A default case can be done with `pattern - (pattern | {cases})`.
> >
> > This is faster than using alternations: O(1) vs O(n).
> 
> We already have `pattern/func`, which replaces the match by
> the result of `func`. This is a good deal more general: the original
> string, the position and all the captures get passed to `func`.

  You're thinking of lpeg.Cmt(), which passes the original string, position
and capture to a function.  What you described, "pattern / function" just
gets passed the capture, which is replaced by what the function returns.

  That aside, unless the performance of LPeg is impacting the program, don't
try to micro-optimize the code [1].  And when it does, there are things you
an do to improve performance, like:

	* at the bottle neck, reorder the choices to the most common cases
	  are handled first.

	* simplify the grammar if you can.

	* perhaps modify LPeg such that "pattern / table" will do what you
	  want:

		local expr   = (P(1) - P")")^1
		local simple = R("az")^1 / { 
		  one   = P"(" * expr      * P")",
		  two   = P"{" * R"09"^1   * P"}",       
		  three = P"[" * R("AZ")^1 * P"]"        
		}
		local things = (simple * P";")^1

  Also, I'm not a fan of the "pattern | table" as I'm still using Lua 5.1
[2].

  -spc

[1]	At work, I'm using Lua 5.1 (not LuaJIT because it doesn't support
	our architecture) and LPeg 0.12 to parse SIP messages.  It hasn't
	become a performance issue yet.

[2]	Lua 5.2 wasn't compelling enough to upgrade the code (and I was
	still holding out hope of using LuaJIT but that's looking more and
	more unlikely) and upgrading to Lua 5.3 would be a significant
	amount of work---not something I want to do while we're pushing out
	a new product.