Post by lars on Jan 26, 2017 7:14:55 GMT
I tried to write a brainfuck compiler in lua. Could be buggy
file = "bf.lua"
debugmode = false
input = {}
brainfuckinput = ""
pointer = 1
scope = 0
function debug(...)
if (debugmode) then
print(...)
end
end
filei = io.open(file, "r")
debug("Opened File '"..file.."'")
if (filei == null) then
error("File '"..file.."' not Found")
end
function getValue(ptr)
if (input[pointer] == null) then
input[pointer] = 0
end
return input[pointer]
end
while (true) do
inp = filei:read()
if (inp == null) then
break
end
brainfuckinput = brainfuckinput..inp
end
debug("Size of input: "..string.len(brainfuckinput))
debug("Input: "..brainfuckinput)
inparr = {}
brainfuckinput:gsub(".",function(c) table.insert(inparr,c) end)
i = 1
while(i <= #inparr) do
char = inparr[i]
debug("Next char: "..char)
if (char == ">") then
pointer = pointer + 1
debug("Increased the pointer")
debug("Pointer: "..pointer)
elseif (char == "<") then
pointer = pointer - 1
debug("Decreased the pointer")
debug("Pointer: "..pointer)
elseif (char == "+") then
input[pointer] = getValue(pointer) + 1
elseif (char == "-") then
input[pointer] = getValue(pointer) - 1
elseif (char == ".") then
sys.print(string.char(getValue(pointer)))
elseif (char == ",") then
input[pointer] = string.byte(sys.input())
elseif (char == "[") then
if (getValue(pointer) == 0) then
debug("Condition met, skipping while.")
--we need to search the ending tag
scope = 0
closing = 0
for j = i, #inparr do
if (inparr[j] == "[") then
-- + 1 scope
scope = scope + 1
end
if (inparr[j] == "]") then
-- - 1 scope
scope = scope - 1
end
if (scope == 0) then
debug("Found closing on "..j)
closing = j
break
end
end
debug("i = "..i..", j = "..closing)
i = closing
end
elseif(char == "]") then
if not (getValue(pointer) == 0) then
debug("While closed, jumping up. (Val: "..getValue(pointer))
--we need to search the ending tag
scope = 0
opening = 0
j = i
--for j = i, #inparr do
while (j > 0) do
if (inparr[j] == "[") then
-- + 1 scope
scope = scope + 1
end
if (inparr[j] == "]") then
-- - 1 scope
scope = scope - 1
end
if (scope == 0) then
debug("Found opening on "..j)
opening = j
break
end
j = j - 1
end
debug("i = "..i..", j = "..opening)
i = opening
end
else
debug("Char not known. Ignoring.")
end
i = i + 1
sleep(1000)
end