[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lpeg query
- From: David Heiko Kolf <david@...>
- Date: Sun, 19 Jan 2014 17:22:45 +0100
Gavin Wraith wrote:
> Have I have got this right? For X an lpeg pattern and s a string,
> then, by default, X:match (s) returns a number (index of first
> failure) unless X has captures, in which case the captures are
> returned. So in the code:
>
> require "lpeg" local P, C = lpeg.P, lpeg.C local SPACE, END = P " ",
> P (-1) local BLANK, WORD = SPACE^0, (1 - SPACE)^1 local WORDS =
> BLANK*(C(WORD)*BLANK)^0*END
>
> the table
>
> { WORDS:match " alpha beta " }
>
> is { "alpha", "beta" } but the table
>
> { WORDS:match " " }
>
> is { 2 }. I would have liked { } for smoothness of notation. This
> seems to be a trap for unwary persons like myself.
>
> 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?
Hello,
here is part of the documentation for the match function:
> If the match succeeds, returns the index in the subject of the first
> character after the match, or the captured values (if the pattern
> captured any value).
If you want it to return nil, make sure that your pattern does not match
in this case. You would simply have to change your definition of WORDS
to require at least one captured word:
local WORDS = BLANK*(C(WORD)*BLANK)^1*END
This should then work as expected.
Best regards,
David Kolf