Search code examples
forthgforth

How to write a while() loop in Gforth


I'd like to write a while() loop in Gforth. Unfortunately, the only tutorial online isn't useful due to a lack of examples, and examples on counted loops (what I'm not looking for) appear fundamentally different.

What are some concrete examples of how to represent something like this?

while (x > 3) { print(x); x--; }

Or really, just some concrete way to represent anything of the form:

while (predicate) { expression(s) }

Solution

  • Your first piece of code translates to:

    \ Assuming x is on the top of the stack.
    begin dup 3 > while dup . 1- repeat
    
    \ Or if x is in memory.
    begin x @ 3 > while x ? -1 x +! repeat
    

    And the second:

    begin predicate while expressions repeat