|
Warning: this is an htmlized version!
The original is here, and the conversion rules are here. |
-- This file:
-- http://angg.twu.net/LUA/lpeg-minitut.lua.html
-- http://angg.twu.net/LUA/lpeg-minitut.lua
-- (find-angg "LUA/lpeg-minitut.lua")
-- Author: Eduardo Ochs <eduardoochs@gmail.com>
--
-- (defun l () (interactive) (find-angg "LUA/lpeg-minitut.lua"))
-- (find-es "lua-intro" "lpeg-quickref")
-- (find-es "lpeg")
-- (find-es "lua-intro" "lpeg-re-infix-1")
--
-- See: (find-angg "LUA/Re.lua")
-- «.arit1» (to "arit1")
require "re"
syntreeg = function (...)
local A = {...}
local S = SynTree {[0] = A[2]}
for i=1,#A,2 do table.insert(S, A[i]) end
return S
end
packcaptures = function (...)
local A={...}
return #A==1 and A[1] or packcaptures0(...)
end
packcaptures_pars = function (...) return "("..table.concat({...}, " ")..")" end
packcaptures_tree = function (...) return syntreeg(...) end
usepars = function () packcaptures0 = packcaptures_pars end
usetree = function () packcaptures0 = packcaptures_tree end
usetree()
defs = { f = packcaptures }
c = function (pat) return re.compile(pat, defs) end
retest = function (pat) return function (s) print(re.match(s, c(pat))) end end
-- «arit1» (to ".arit1")
-- (find-es "lpeg" "re-quickref")
--[[
"string" literal string
[class] character class
p * zero or more repetitions
p + one or more repetitions
name non terminal
p1 p2 concatenation
p1 / p2 ordered choice
( p ) grouping
{ p } simple capture
(name <- p)+ grammar
p -> name function/query/string capture equivalent to p / defs[name]
--]]
test_arit1 = retest [[
e <- e3
e3 <- (e2 ({"+"} e2)*) -> f
e2 <- (e1 ({"*"} e1)*) -> f
e1 <- (e0 ({"^"} e0)*) -> f
e0 <- "(" e3 ")" / {[0-9]+}
]]
--[[
* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
dofile "lpeg-minitut.lua"
= syntreeg(1, "+", 2)
= syntreeg(1, "+", 2, "*", 3)
= syntreeg(1, "+", 2, "*", syntreeg(1, "/", 2))
= syntreeg(1, "+", 2, "*", syntreeg(1, "/", syntreeg(4)))
usepars(); test_arit1 "1*2+3^4*5^6+7^8"
usetree(); test_arit1 "1*2+3^4*5^6+7^8"
= packcaptures(1, "+", 2)
= packcaptures(1, "+", 2, "*", 3)
= packcaptures(1, "+", 2, "*", packcaptures(1, "/", 2))
usetree(); test_arit1 "1*2+3^4*5^6+7^8"
usetree(); test_arit1 "1*2+3^4*5^6+7^8"
print(str)
--]]
-- (find-es "lpeg" "re-quickref")
sfpack = function (...) return {...} end
sfdefs = {
pack = sfpack,
validword = function (subj, pos, word)
if word:match"^b" then return pos end
end,
}
sfc = function (pat) return re.compile(pat, sfdefs) end
sftest = function (pat) return function (s) PP(re.match(s, sfc(pat))) end end
sf1 = sftest [[
top <- %s* {} Thing {}
number <- { [-+]? [0-9]+ ( "." [0-9]+ )? }
quotedlit <- { '"' [^"]* '"' }
dquotedlit <- { "'" [^']* "'" }
word <- { [!-~]+ }
validword <- { word => validword }
Number <- {| ""->"Number" number |}
QuotedLit <- {| ""->"QuotedLit" (quotedlit / dquotedlit) |}
Word <- {| ""->"Word" validword |}
Thing <- Number / QuotedLit / Word
]]
-- Local Variables:
-- coding: utf-8-unix
-- End: