Skip to content

Instantly share code, notes, and snippets.

@permil
Last active February 6, 2018 15:21
Show Gist options
  • Save permil/d9be72549a9193dc766682df5018b577 to your computer and use it in GitHub Desktop.
Save permil/d9be72549a9193dc766682df5018b577 to your computer and use it in GitHub Desktop.
bf interpreter written in Lua
prog = ">+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]>++++++++[<++++>-]<.>+++++++++++[<+++++>-]<.>++++++++[<+++>-]<.+++.------.--------.[-]>++++++++[<++++>-]<+.[-]++++++++++."
p_ptr = 1
tape = {}
ptr = 0
insts = {
['>'] = function() ptr = ptr + 1 end,
['<'] = function() ptr = ptr - 1 end,
['+'] = function() if tape[ptr] == nil then tape[ptr] = 1 else tape[ptr] = tape[ptr] + 1 end end,
['-'] = function() tape[ptr] = tape[ptr] - 1 end,
['.'] = function() io.write(string.char(tape[ptr])) end,
[','] = function() tape[ptr] = io.read() end,
['['] = function()
if tape[ptr] == 0 then
local cnt = 1
while true do
p_ptr = p_ptr + 1
local c = string.sub(prog, p_ptr, p_ptr)
if c == '[' then
cnt = cnt + 1
elseif c == ']' then
cnt = cnt - 1
if cnt == 0 then break end
end
end
end
end,
[']'] = function()
local cnt = 1
while true do
p_ptr = p_ptr - 1
local c = string.sub(prog, p_ptr, p_ptr)
if c == ']' then
cnt = cnt + 1
elseif c == '[' then
cnt = cnt - 1
if cnt == 0 then break end
end
end
p_ptr = p_ptr - 1
end
}
while p_ptr < #prog do
insts[string.sub(prog, p_ptr, p_ptr)]()
p_ptr = p_ptr + 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment