Trying to make a brainfuck interpreter in python from scratch just for fun, I'm almost done with the code however this small error is coming up whenever I try interpreting ",[>++++<]" Which is supposed to input a number, and multiply it by 4. It stops and gets this error
File ".\bfInterpreter.py", line 42, in endWhile
if self.stack[self.pointer]: self.place = self.inWhile.pop(-1)
IndexError: pop from empty list
Any ideas?
here is the code that the error is in:
import sys
import time
class Operator:
def __init__(self) -> None:
self.pointer = 0
self.place = 0
self.inWhile = []
self.stack = [0]
def plus(self):
self.stack[self.pointer]+=1
def minus(self):
self.stack[self.pointer]-=1
def left(self):
if self.pointer > 0: self.pointer -= 1
else: raise IndexError
def right(self):
self.pointer += 1
try: self.stack[self.pointer] = 0
except: self.stack.append(0)
def output(self):
print(ascii(self.stack[self.pointer]))
def inp(self):
val = input("Num: ")
try: self.stack[self.pointer] = int(val)
except:
print("Please input a number")
self.inp()
def startWhile(self):
self.inWhile.append(self.place)
print(self.inWhile)
def endWhile(self):
print(self.inWhile)
if self.stack[self.pointer]: self.place = self.inWhile.pop(-1)
def interpret(self, bf):
self.place = 0
while self.place < len(bf):
if bf[self.place] == "+": self.plus()
elif bf[self.place] == "-": self.minus()
elif bf[self.place] == "<": self.left()
elif bf[self.place] == ">": self.right()
elif bf[self.place] == "[": self.startWhile(bf)
elif bf[self.place] == "]": self.endWhile()
elif bf[self.place] == ",": self.inp()
elif bf[self.place] == ".": self.output()
else: raise SyntaxError
self.place += 1
print(self.stack)
def main():
start = time.time()
op = Operator()
op.interpret(",[>++++<]")
print(f"Ended in {time.time() - start} second(s)")
if __name__ == "__main__": main()
Edit: self.stack is basically the memory that brainfuck is allowed to access and edit, so the "[" starts a while loop, checking if a certain spot in the stack has reached 0 every cycle, and if it's not 0, it repeats the code in the brackets