Looping down to zero in Forth

  • The FTB Forum is now read-only, and is here as an archive. To participate in our community discussions, please join our Discord! https://ftb.team/discord

PhilHibbs

Forum Addict
Trusted User
Jan 15, 2013
3,174
1,128
183
Birmingham, United Kingdom
A loop in Forth with an ending value of SORTSLOTS and a starting value of 0 will cover an entire inventory.
Code:
SORTSLOTS 0 ?DO
...
LOOP
The loop stops before executing the last iteration, so on a regular 27-slot chest, the loop goes from 0 to 26, which is fine. The slots are zero-based to a Sortron so there is no slot 27.

What if I want to loop in reverse? If I do this:
Code:
-1 SORTSLOTS 1 - ?DO
...
-1 +LOOP
...the loop executes on slot -1! How come the end value is inclusive on negative loops?
 

ratchet freak

Well-Known Member
Nov 11, 2012
1,198
243
79
you could do the manual begin until repeat loop...

Code:
SORTSLOTS BEGIN 1 - DUP 0= UNTIL (code) REPEAT DROP

you just need to be careful to DUP the top when you use it i the loop ;)

I do got a version using the R stack so it's not that much of an issue