Created
October 7, 2016 01:44
-
-
Save inmatarian/2aef62e05ec7bee449896da6fed65b02 to your computer and use it in GitHub Desktop.
Brainfuck compiler to lua, also because why not.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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