Warning: this is an htmlized version!
The original is here, and
the conversion rules are here.
-- -*- coding: raw-text-unix -*-
-- preproc.lua - a non-intrusive generic preprocessor
-- Author:     Eduardo Ochs <[email protected]>
-- Version:    2008sep26
-- (find-es "lua5" "preproc")

loadlpeg()    -- (find-angg "LUA/lua50init.lua" "loadlpeg")

cmdA = {}     -- one entry for each command (arg parser)
cmdC = {}     -- one entry for each command (body)
cmdname = ""  -- accumulator variable
cmdargs = {}  -- accumulator variable
cmdsetname = function (s, p, name)
    if cmdA[name] then cmdname = name; return true end
  end
cmdsetargs = function (s, p, ...)
    cmdargs = pack(...)
    return true
  end
cmddef = function (name, ArgPat, f)
    cmdA[name] = ArgPat:Cmt(cmdsetargs)
    cmdC[name] = f
  end
CmdName   = (lpeg.R"AZ" ^1):Cmt(cmdsetname)
CmdArgs   = lpeg.P(function (s, p) return cmdA[cmdname]:match(s, p) end)
CmdNoArgs = lpeg.P(function (s, p) error("No args for "..cmdname) end)
CmdRun    = lpeg.P(function (s, p) return p, cmdC[cmdname](unpack(cmdargs)) end)
Cmd       = lpeg.P"\\" * CmdName * (CmdArgs + CmdNoArgs) * CmdRun
-- (find-angg "LUA/lua50init.lua" "lpeg_togsub")
-- (find-angg "LUA/lua50init.lua" "lpeg_gsub_")
CmdGsub   = Cmd:togsub():Ct()
preproc   = function (str) return CmdGsub:gsub_(str) end

-- The only "exports" from the code above
-- are cmddef and preproc.

-- Useful.
-- (find-angg "LUA/lua50init.lua" "lpeg_balanced")
Curly  = lpeg.Balanced("{", nil, "}")
Space  = lpeg.S" \t\n"
SCurly = Space^0 * Curly
Curly00 = lpeg.P ""
Curly0 = Space^0
Curly1 = SCurly
Curly2 = SCurly * SCurly
Curly3 = SCurly * SCurly * SCurly




--[[
-- A demo:
-- (find-es "lua5" "preproc")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
ee_dofile "~/LUA/preproc.lua"   -- (find-angg "LUA/preproc.lua")
F = function (fmt) return function (...) return format(fmt, ...) end end
cmddef("ONE",   Curly1, F"(one: %s)")
cmddef("TWO",   Curly2, F"(two: %s %s)")
cmddef("THREE", Curly3, F"(three: %s %s %s)")
= preproc "\\ONE{foo}{bar}_\\TWO{plic}{ploc}{woo} bleh"
      --> "(one: foo){bar}_(two: plic ploc){woo} bleh"
= preproc "\\ONE{foo}{bar}_\\TWO{plic} no second arg"
      --> error: No args for TWO

--]]