T Williams T Williams - 4 months ago 11
Brainfuck Question

My seemingly functional BF interpereter cannot run standard BF programs

This is the code for my interpereter:

program=list(raw_input('Program: '))
array = [0 for i in range(100)]
pointer=0
prgpointer=0
run = True
while run:
try:
command = program[prgpointer]
if command == '>':
pointer += 1
if command == '<':
pointer -= 1
if command == '+':
array[pointer]=array[pointer]+1
if command == '-':
array[pointer]=array[pointer]-1
if command == '.':
print(array[pointer])
if command == '[' and array[pointer]==0:
while program[prgpointer]!=']':
prgpointer+=1
if command == ']' and array[pointer]!=0:
while program[prgpointer]!='[':
prgpointer-=1
except:
run = False
prgpointer+=1


When I run this program:

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.


I get the result of

-1
-3
4
4
7
0
-2
7
10
4
-4
1
1


This porgram is a functional 'hello world' program in any other bf interpereter. Even when the output is converted to ASCII it is not 'Hello World'
Is there any major problem that can be pointed out about my interpereter?
Are the commands correct?

Answer
  1. To print the char value at your data pointer you need sys.stdout.write(chr(array[pointer])) because otherwise you'll just print numbers -- after all numbers are what's in your list.

  2. The language spec says that [ and ] represent jumps to the matching bracket. You are jumping to the next/previous bracket.

Comments