Search code examples
forthgforth

How can I check whether enough arguments are passed to a word in Forth?


I have written this word to multiply two floating point numbers:

: fpmult { F: a F: b }
  cr
  ." Result: "
  a b f* f.
;

This works fine as long as there are either two fp's on the fstack or the commandline. Even the combination of one fp on the fstack plus one fp in the commandline which launches the word is possible:

1.3e  ok
5.78e fpmult 
Result: 7.514  ok

But if only one fp is missing it throws an error (of course):

5.78e fpmult 
:9: Floating-point stack underflow
5.78e >>>fpmult<<<
Backtrace:
$7F5CDB1367A0 f>l 

How can I make the word check for the existence of both variables a and b right at the start? Or is there a better way to solve the problem?


Solution

  • You can use the standard word fdepth ( -- u )

    : fpmult. ( F: r1 r2 -- )
      fdepth 2 u< if cr ." insufficient number of arguments" abort then
      f* f.
    ;
    

    NB: abort empties the data stack and floating-point stack.


    JFYI, the standard local variable syntax is {: :}