lua-users home
lua-l archive

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


Sam Roberts wrote:
Uh, self-documenting if you know lpeg, complete goobledygook if you
don't!

Of course, that's the case for lot of languages.
The self-documenting part is on the fact that elements get explicit names, unlike most regular expressions (I know the named capture stuff..).

At the cost of even more verbosity, one can make it perhaps more readable, if knowing the base operators (^0, ^1, +, *):

----- LPegWrapper.lua
#!Lua51.exe

m = require"lpeg"

Pattern = m.P
String = m.P
Range = m.R
Set = m.S
Ref = m.V
Capture = m.C
IndexCapture = m.I
TableCapture = m.T
function Not(p) return 1 - p end

----- LPegTests.lua

#!Lua51.exe

dofile"LPegWrapper.lua"
dofile[[DumpObject.lua]]

space = Set" \t"
sp = space^0
equal = String"="
name = Capture(Not(space + equal)^1, "name")
sval = Capture(Not(space)^1, "value")
singleQuote = String"'"
doubleQuote = String'"'
quotedValue = singleQuote * Capture(Not(singleQuote)^0, "value") * singleQuote doubleQuoteval = doubleQuote * Capture(Not(doubleQuote)^0, "value") * doubleQuote pair = TableCapture(sp * name * sp * equal * sp * (quotedValue + doubleQuoteval + sval))
args = TableCapture(pair^0)

function ExtractArgs(s)
    mr = m.match(s, args)
    print(DumpObject(mr))
end
ExtractArgs[[class=q href="http://images.goo gle.se/imghp?hl=sv&tab=wi" onClick='return qs(this);' test=foo]]

----- Result

local T =
{
  [1] =
  {
    name = "class",
    value = "q"
  },
  [2] =
  {
    name = "href",
    value = "http://images.goo gle.se/imghp?hl=sv&tab=wi"
  },
  [3] =
  {
    name = "onClick",
    value = "return qs(this);"
  },
  [4] =
  {
    name = "test",
    value = "foo"
  }
}

--
Philippe Lhoste
--  (near) Paris -- France
--  http://Phi.Lho.free.fr
--  --  --  --  --  --  --  --  --  --  --  --  --  --