lua-users home
lua-l archive

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


<% a=1 b=1 %>B"B"B<%= abc %><h1>h1</h1><%! a.html %>cc
has been translate to:
a=1 b=1 print("B\"B\"B")printf( abc )print("<h1>h1</h1>")include( a.html )print("cc")print("cc")

2010/12/18 zhiguo zhao <zhaozg@gmail.com>
Hi, all.

 I study lp compile in cgilua, then I want to rewrite it with lpeg. But I think I not have enough knowledge of lpeg, so I think I used more lpeg.Cg and lpeg.Cb.
Welcome any solution to make it clear and faster,

local lpeg = require"lpeg" 

local B = lpeg.P("<%")      --begin
local E = lpeg.P("%>")      --end
local I = lpeg.S("=!@ ")    --instruction

local NB = (1 - B)^0
local NE = (1 - E)^0

function parse(s,text,script)
    local IN    = lpeg.Cg(I,'INS')      --instruction named
    local TN    = lpeg.Cg(NB,'TEXT')
    local SN    = lpeg.Cg(NE,'SCRIPT')  --script named

    local TP = lpeg.Cmt(TN*lpeg.Cb('TEXT'),text)                                   --text process
    local SP = lpeg.Cmt(IN^-1 * SN * lpeg.Cb('INS') * lpeg.Cb('SCRIPT'),script)   --script process
    local LS = B * SP * E               --script block

    local handle = (TP * LS)^0 * TP     --all context

    return lpeg.match(handle,s)
end

function translate(s)
    local res = {}
    ptext = function(_,_,s)
        if(s~='') then
            table.insert(res,string.format('print(%q)',s))
        end
        return true
    end

    pscript = function(all, _, i, s)
        if( i=='=') then
            table.insert(res,string.format('printf(%s)',s))
        elseif(i=='!') then
            table.insert(res,string.format('include(%s)',s))
        elseif(s=='@') then
            table.insert(res,string.format('@@@@(%s)',s))
        else
            table.insert(res,s)
        end
        return true
    end
    if(parse(s,ptext,pscript)) then
        print(#res)
        return table.concat(res)
    end
    return nil
end

local content = '<% a=1 b=1 %>B"B"B<%= abc %><h1>h1</h1><%! a.html %>cc'
--local content = 'cc'
print(content)
print('after translate')
print(translate(content))