udamonic.com
  • Learn
  • Design
  • Videos
  • Resources
  • Firmware
  • Buy
  • About

if ... else 
​

Like other programming languages, Forth has if ... else ... , but the structure is quite different to that with which you are used to. if treats the top-most stack entry as a boolean, and conditionally executes the code that follows. (Any non-zero value is considered as true.) then goes at the end of the code to be conditionally executed.

Here is some example code that shows you how to use if:
: test ( n -- , tests if n is true )
   if
      ." That is true"
      cr
   else
      ." That’s not true"
      cr
   then
;
Note that the if statement is terminated by then. This is somewhat unusual if you’re used to other programming languages. To show how this new word works, if we typed:
​5 test
we’d get That is true but, if we typed:
0 test
we’d then get That’s not true.
​
For a simple if statement with no need of else, the format is simply:
​: true? ( n -- , prints if n is true )
   if
      ." That is true"
      cr
   then
;

CASE

Some versions of Forth include support for case statements. This is not part of the standard FlashForth build, but you can add it yourself...
\ 
\    Case for FlashForth                                              
\    Filename:      case.txt                                          
\    Date:          26.01.2014                                        
\    FF Version:    5.0                                               
\    Copyright:     Mikael Nordman 
\    Author:        Mikael Nordman                                    
\ A case implementation posted by Jenny Brien on c.l.f.
\ Modified to use for..next instead of do..loop

-case
marker -case
hex ram

\ of compare
: (of) ( n1 n2 -- n1 flag ) 
  inline over
  inline -
  0=
;

: case  (  -- #of )
  0
; immediate

: of  ( #of -- #of orig )  
    postpone (of)  ( copy and test case value)
    postpone if    ( add orig to control flow stack )
    postpone drop  ( discard case value if case is matching )
; immediate

: default ( #of -- #of orig )
  postpone true      ( Force to take the default branch )
  postpone if        ( add orig to control flow stack )
  postpone drop      ( discard case value )
; immediate

: endof ( orig1  -- orig2 #of )
   postpone else 
   swap 1+
; immediate

: endcase  ( orig1..orign #of  -- )
    postpone drop  ( discard case value )
    for
      postpone then ( resolve of branches )
    next
; immediate

As an example of how to use case: 
​
: case-test
  case
  2 of ." two " 2222 endof
  3 of ." three " 3333 endof
  default  ." default " 9999 endof
  endcase
  u.
;

2 case-test
3 case-test
8 case-test

: case-test2
  case
  11 of endof
  default endof
  endcase
;

Now, let's learn how to create loops in Forth.
Site powered by Weebly. Managed by Hostwinds
  • Learn
  • Design
  • Videos
  • Resources
  • Firmware
  • Buy
  • About