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 Gavin Wraith once stated:
> 
> What is the most elegant way to amend WORDS so that { WORDS:match " " }
> has the value { }?  Or is that not possible seeing that the operation
> of composing values has no unit; i.e. no value @ so that @,x and x,@ are
> just x?
> 
> Does it make any sense to ask for a variant of Lpeg in which lpeg.match
> does not return a number but nil by default? The capture lpeg.Cp could
> then be used to produce the current behaviour.

  You can do what you ask with LPeg now.  I take it that you want to return
either captures of words, or just nil if there are none.  But, what if you
change it up a bit, and return an optional list of words, followed by a nil?

	local Cc = lpeg.Cc
	local WORDS = BLANK*(C(WORD)*BLANK)^0*END*Cc(nil)

  Cc() will match the empty string and return its parameter, in this case,
nil.  And that does what you are asking:

	print(WORDS:match "one two three")
	one     two     three   nil
	print(WORDS:match " ")
	nil

  LPeg is quite powerful, and yes, it does take time to work through all it
can do.

  -spc (You could also add the call to Cc() in the defintion of END with
	the same results ... )