lua-users home
lua-l archive

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

On Tue, 30 Nov 2010 13:37:14 +0200, Tony Finch <> wrote:

On Tue, 30 Nov 2010, Juris Kalnins wrote:

 - matching (length, value) encoded strings:
    for example some binary stream, like network packet, that
    at some point stores length, followed by that many bytes.

Use a match-time capture, e.g. for a one-octet count,

  local m = require "lpeg"

  local p = m.Cmt(m.P(1), function (str, pos)
    local len = str:byte(pos)
    return pos+1+len, str:sub(pos+1, pos+len)

Very thanks!

The capture value is a string comprising the len octets following the
count octet.

 - matching output of another lpeg capture.
    for example, some keyword that is case-insensitive.
    can it be matched using P "string" over something?

This might be another job for match-time captures, e.g.

  function kw_pattern(kw)
    return m.Cmt(m.P(#kw), function (str,pos)
      local fin = pos+#kw
      if kw == str:sub(pos,fin):lower()
      then return fin end

Thank you, after fixing the following works:

function kw_pattern(kw)
    return m.Cmt(m.P(#kw), function (str,pos)
        if kw == str:sub(pos-#kw,pos-1):lower() then return true end