Development Tips

Just a few handy methods I’ve developed along the way ...

Balancing The Return Stack

Forth Does have a ‘local vartiable’, it’s called The Return stack ;-), but it must be balanced or your program will crash.

Example program

This program splits a number into digits, and utilises the Return Stack as a local variable, but how to make sure that the Return Stack is balanced ?
: split
   >R                      \ Save the input on the Return Stack
   BEGIN
       R> ?DUP 0 > WHILE   \ Fetch from the Return Stack, duplicate because " 0 >" and "/MOD" both use it, then continue WHILE greater than zero. ?DUP is used instead of DUP to prevent a zero being left on the stack after the program has completed.
       10 /MOD >R . cr     \ divide by 10 and save the result on the Return Stack, print each remainder on a new line
   REPEAT
;

123456789 split
9
8
7
6
5
4
3
2
1

Balancing Act

In this case, I used a variable (rb) to tally my Return Stack pushes and pulls. A ‘rb’ total of 0 shows the Return Stack is balanced.

Of course, if the Return Stack isn’t balanced, this is bad and if it doesn’t crash now, it will cause problems later.

Return Stack Operation code Description
Push >R rb @ 1+ rb ! Add one to ‘rb’
Pull R> rb @ 1- rb ! Subtract one from ‘rb’

Example Program Including Return Stack Accounting

This time every Return Stack ADD is worth 1 and REMOVE is worth -1. A total of 0 shows the Return Stack is balanced, so no visual comparison is required.

0 variable rb
: split-rbalance cr
>R rb @ 1+ rb !
BEGIN
R> rb @ 1- rb !
?DUP 0 > WHILE
10 /MOD
>R rb @ 1+ rb !
.  cr
REPEAT
cr
rb @ 0= if
."  The Return Stack is balanced " cr cr
else
."  UNBALANCED ! The Return Stack is NOT balanced! rb =  " rb @ . cr cr
then
;

Return Stack Accounting Output

123456789 split-rbalance

 9
 8
 7
 6
 5
 4
 3
 2
 1

 The Return Stack is balanced

ok.

Table Of Contents

Previous topic

Svd2forth-v2

Next topic

Library

This Page