Skip to content

Instantly share code, notes, and snippets.

@inmatarian
Created October 7, 2016 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inmatarian/2aef62e05ec7bee449896da6fed65b02 to your computer and use it in GitHub Desktop.
Save inmatarian/2aef62e05ec7bee449896da6fed65b02 to your computer and use it in GitHub Desktop.
Brainfuck compiler to lua, also because why not.
preamble = [=[
local p, d = 1, {}
function g() return d[p] or 0 end
function s(v) d[p] = v end
function o() io.write(string.char(g())) end
function i() s(string.byte(io.read(1))) end
]=]
subst = {
['>'] = "p=p+1\n",
['<'] = "p=p-1\n",
['+'] = "s(g()+1)\n",
['-'] = "s(g()-1)\n",
['.'] = "o()\n",
[','] = "i()\n",
['['] = "while g() ~= 0 do\n",
[']'] = "end\n",
}
function compile(s)
return preamble .. io.open(s):read('*a'):gsub("[^%+%-<>%.,%[%]]+",""):gsub(".", subst)
end
function run(s)
assert(loadstring(compile(s), s))()
end
if (...) == '--run' then
run(select(2,...))
else
io.write(compile(...))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment