I'm writing a simple stack-based language in C and was wondering how I should go about implementing a loop structure of some kind, and/or lookahead symbols. Since the code is a bit long for this page (over 200 lines) I've put it in a GitHub repository.
EDIT: The main program is in file stack.c
.
EDIT: The code just takes in input in words
, kind of like FORTH. It uses scanf
and works left to right. Then it uses a series of if
s and strcmp
s to decide what to do. That's really it.
The Forth approach is to add a separate loop stack alongside the data stack. You then define operations that work with this loop stack. For example:
5 0 DO I . LOOP
Will print
0 1 2 3 4
The way this works is:
DO
moves the index (0) and the control (5) over to the loop stack.I
copies the top of the loop stack to the data stack.LOOP
increments the index (top of loop stack). If the index is less than the control (one below the top of loop stack), then it reruns the commands from DO
back to LOOP
. If the index is >=, then it pops the index and control from the loop stack, and control resumes as normal.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With