lua-users home
lua-l archive

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


On 9/4/16, Soni L. <fakedme@gmail.com> wrote:
> Is it still LPeg if it's not LPeg?I'm pretty sure I can't use LPegLabel
> in things that only come with standard LPeg built-in. That is, I'm
> pretty sure LPegLabel doesn't come built into Luvit and I'd have to
> install it as yet another useless external dependency that's about 95%
> redundant, because Luvit includes LPeg by default.

It's an extension, so technically no, but you can replace every
instance of LPeg with LPegLabel without issue. However, if you do not
wish to modify Luvit (understandably so), then you must indeed add
LPegLabel as another dependency.

> Is a pure-LPeg solution too hard?

I wouldn't really consider it hard, but it isn't so simple either. You
may continue to use `error` and catch it with a protected call
(`pcall`). If you're concerned about the catching of non-parsing
errors, you could throw a table with a tag and check if that tag
exists, otherwise rethrow the error (you will lose the stack trace
though).

    local function fail (msg)
      return lpeg.P(function(_, i)
        error({ tag = "match-fail", msg = msg .. " at position " .. i })
      end)
    end

    local backslashEscaped = ... + lpeg.P("\\") * fail("Unknown
backslash escape")

    local function parse(text)
      local ok, result = pcall(function () return Line:match(text) end)
      if ok then
        return result
      elseif type(result) == "table" and result.tag == "match-fail" then
        return nil, result.msg
      else
        error(result)
      end
    end

It's not ideal, but it gets the job done. You could also follow the
approach suggested by Sean in
http://lua-users.org/lists/lua-l/2016-07/msg00661.html. It's a bit
less efficient since it'll do some unnecessary backtracking, but it
shouldn't matter for most cases. If the use of Carg bothers you, you
could use a global variable instead (just make sure not to run matches
concurrently).

I hope this helps :-)

-- 
Matt