Programming Question And Answers

Answered from the Perspective of Mecrisp-Stellaris Forth.

Editing Words

I’m curious with how you deal with changing the number of items a Word is expecting/leaving on the stack? let’s say you defined a word FOO that expected 2 numbers on the stack, and left 1 number on the stack. Now you change FOO to return 2 Stack items.

Q: How do you check that everything that calls FOO is now ready for the extra Stack item ?

A: I just reload and run the modified program and check the Stack. Here is an example:

Example

Here we define FOO and FOO2X which satisfies the above question.

: FOO ( u1 u2 - - u3 ) + ; add two parameters, return the addition on the Stack

: FOO2X ( - - FOO * 2 ) FOO 2 * ; pass two parameters to FOO then multiply the result by 2 and place the result on the Stack

1 2 FOO2X . .s check the Stack contents, there should be nothing on it.

Uploading the code produces this output:

1 2 FOO2X . 6  ok.
.s [0 ] 42  ok.                       \ Ignore the "42" the Stack counter "[0 ]" shows nothing is left on the stack

The Words performed as expected.

Editing Foo

Foo is now edited so that it will return two numbers, the first is the addition of the parameters 1 and 2, the second is the number 2

: FOO ( u1 u2 - - u3 ) + 2 ; add two parameters, return the addition on the Stack PLUS the number 2, this is our extra Stack item.

: FOO2X ( FOO - - FOO 2 * ) FOO 2 * ; nothings changed here

1 2 FOO2X . .s check the Stack contents, there should be nothing on it.

1 2 FOO2X . 4  ok.
.s  [1 ] 42 3  ok.                    \ PROBLEM ! there is a UNEXPECTED STACK ITEM shown by "[1 ]", it's the number 3 (ignore the 42 again)

Something has gone wrong here (as expected) and the clue is that the stack has a number left on it, the number 3 which was the addition of the parameters 1 and 2 given to FOO.

FOO2X was only expecting ONE parameter and was presented with two, so it took the first one the “extra number 2” we added above.

We were not expecting anything on the Stack and finding the Stack is NOT EMPTY is how I handle checking that everything that invokes FOO is now ready for the extra parameters.