lua-users home
lua-l archive

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


I've been playing around a bit with LPEG and I really like it. LPEG is to Regexp as Lua is to Perl.

Does anyone have any bright ideas on how to parse indentation-based syntaxes with LPEG. So far, the best I have is:

function indent(s)
   local row = lpeg.C((1 - lpeg.P('\n'))^0) * lpeg.P('\n')
   local i = lpeg.P('    ')
   function node(name, ...) return {name=name, children={...}} end
local maxdepth = 4
   local indent = {lpeg.P(true)}
   for j=2,maxdepth do indent[j] = indent[j-1]*i end
local indentrow = {[maxdepth] = indent[maxdepth] * row / node}
   for j=maxdepth-1,1,-1 do
       indentrow[j] = indent[j] * row *indentrow[j+1]^0 / node
   end
local file = lpeg.Ct(indentrow[1]^0)
   return lpeg.match(file, s)
end

r = indent [[
1
   1.1
   1.2
       1.2.1
       1.2.2
   1.3
       1.3.1
           1.3.1.1
           1.3.1.2
       1.3.2
   1.4
2
   2.1
]]

It works, but it is not so nice that it has a fixed maximum indentation depth and needs to define symbols for all indentation levels.

// Niklas