Skip to content

Instantly share code, notes, and snippets.

@dracconi
Created March 13, 2019 21:00
Show Gist options
  • Save dracconi/b127ee1111a89be64dc344f3ce814daf to your computer and use it in GitHub Desktop.
Save dracconi/b127ee1111a89be64dc344f3ce814daf to your computer and use it in GitHub Desktop.
parsing sexps to lua (currently it works on single line)
function parse(file, start, len)
local tree = {}
local curcmd = '' -- currently parsed command
local ix = start
file:seek("set", ix)
while(ix < len) do
local r = file:read(1)
ix = ix + 1
if r then
if r == "(" then
local ta, dix = parse(file, ix, len)
ix = dix
file:seek("set", ix) -- jumps over body of lower scope
table.insert(tree, ta)
elseif r == ")" then
if curcmd ~= '' then
table.insert(tree, curcmd)
end
curcmd = ''
break
elseif r == " " then
table.insert(tree, curcmd)
curcmd = ''
elseif r:match("%w") or (r == "#" and curcmd == '') then
curcmd = curcmd .. r
end
end
end
return tree, ix
end
function bracket(str, spec)
if spec then
return spec .. str .. spec.reverse
else
if str:sub(0,1) == "#" then
return '['..str:sub(2,str:len()-1)..']'
else
return '{'..str..'}'
end
end
end
function translate(tree)
local buf = ''
for i, v in ipairs(tree) do
if type(v) == "table" then
buf = buf .. bracket(translate(v))
else
if i ~= 1 then
buf = buf .. bracket(v)
else
buf = buf .. '\\' .. v
end
end
end
return buf
end
function stripper(str)
return str:sub(2,str:len()-1)
end
local filename = 'test.sexp'
local contents = io.open(filename, 'r')
local len = contents:seek("end")
local parsed, ex = parse(contents, 0, len)
print(stripper(translate(parsed)))
(frac 1 (die 6 #12))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment