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:
> In message <CABcj=tnFooWJuyc2SpWsOHCf7Rp7exhf7UTDYri0Bk9WjVxfSw@mail.gmail.com>
>           Dirk Laurie <dirk.laurie@gmail.com> wrote:
> 
> > Put another way: the issue is not what can you do with LPeg, it is
> > what can you do that you can't do with Lua patterns, and whether
> > that extra is sufficiently common to justify adding LPeg to Lua.
> 
> That seems sensible to me. I have tried dipping my toe into Lpeg
> but I have found it quite hard - particularly to incorporate
> error handling. 

  I've struggled with that as well.  For a lot of the work I do, it's just
enough to signal an error (the expression returns nil), but yes, there are
times when it would be nice to report a location of the error.  At the very
least, you could try something like:

lpeg = require "lpeg"

pattern = lpeg.P"a"
        + lpeg.P"b"
        + lpeg.Cmt(lpeg.P(1) * lpeg.Cc(false),function(subject,position,capture)
            error( { message = "syntax" , position = position - 1 })
          end)

parse = pattern^1

test = "abacbba"
okay,object = pcall(lpeg.match,parse,test)
if not okay then
  print(test)
  print(object.message,object.position)
else
  print(object)
end

That is, at some point, a match of anything is an error, and throw an error. 
The error handler (either the function that lpeg.Cmt() calls, or where the
error is caught) can take the position and figure out which line and column
it is for better diagnosis.

  -spc