Monday, November 02, 2009

case statements in uForth

case .. of .. endof .. endcase was surprisingly easy to implement:


\ Variable used to keep track of how many 'of' clauses we have.
\
variable _endof

: case ( n -- )
0 _endof !
[compile] >r
; immediate

: of ( n -- )
[compile] r@
[compile] =
postpone if
; immediate

: endof ( -- )
_endof incr
postpone else
; immediate

: endcase ( -- )
_endof @ 0 do postpone then loop
[compile] r>
[compile] drop
; immediate



And, an example:


: test ( number -- )
case
1 of ." one" endof
2 of ." two" endof
3 of ." three" endof
." none"
endcase
;

No comments:

Post a Comment