Search code examples
if-statementforthgforth

USING IF Statement with FORTH produces "Interpreting a compile-only word"


I'm reading Starting Forth: 4. Decisions, Decisions.... I can run 42 42 = .

42 42 =  ok
42 42 = . -1  ok

Predictably, I get -1 which is two's compliment for true. However, if I push a 42 on the stack, and I run

42 .s
42 = IF ." foobar " THEN ; 

I would expect foobar to be outputted and it's not. Instead I get

    42 .s <1> 42  ok
    42 = IF ." foobar " THEN ;  
:2: Interpreting a compile-only word
    42 = >>>IF<<< ." foobar " THEN ; 
Backtrace:
$7F7539250B30 throw 

What's going on here?


Solution

  • I believe these must be compiled into words, for whatever reasons expressions aren't primitives. I believe this is referenced in the book with,

    Notice: an IF…THEN statement must be contained within a definition. You can’t just enter these words in “calculator style.”

    So it would look like this,

    : mycond 42 = IF ." foobar " THEN ;   ok
    42 .s <1> 42  ok
    mycond foobar  ok
    42 mycond foobar  ok
    

    This is again in the gforth docs on Conditional execution

    In Forth you can use control structures only inside colon definitions. An if-structure looks like this: