Implementing Brainf*ck loops in an interpreter

Posted by sub on Stack Overflow See other posts from Stack Overflow or by sub
Published on 2010-04-06T20:43:44Z Indexed on 2010/04/06 20:53 UTC
Read the original article Hit count: 409

Filed under:
|

I want to build a Brainf*ck (Damn that name) interpreter in my freshly created programming language to prove it's turing-completeness.

Now, everything is clear so far (<>+-,.) - except one thing: The loops ([]). I assume that you know the (extremely hard) BF syntax from here on:

  • How do I implement the BF loops in my interpreter?

How could the pseudocode look like? What should I do when the interpreter reaches a loop beginning ([) or a loop end (])?

Checking if the loop should continue or stop is not the problem (current cell==0), but:

  • When and where do I have to check?
  • How to know where the loop beginning is located?
  • How to handle nested loops?

As loops can be nested I suppose that I can't just use a variable containing the starting position of the current loop.

I've seen very small BF interpreters implemented in various languages, I wonder how they managed to get the loops working but can't figure it out.

© Stack Overflow or respective owner

Related posts about brainfuck

Related posts about interpreter