Monday 2 October 2017

Multiple CASE vectors with SWITCHES

Previously we examined how the SWITCH CASE BREAK word works and was improved. In this post an extra construct is added that is simplicity itself, just the way I like it. What we do here is compile a sequence of values and actions after the control word so that it scans the list looking for a match.

This is the word SWITCHES which scans code words there were compiled after it in a word looking for 15-bit literal word since Tachyon V4 can encode a 15-bit literal into a word code.
pub SWITCHES ( val -- )
    SWITCH R>
    BEGIN DUP W@ $7FFF >
    WHILE DUP W@ $7FFF AND SWITCH= IF 2+ W@ JUMP THEN 4+
    REPEAT >R
    ;
Every literal is compared to the switch value and if there is a match then it will execute the next word in the list. Any non-literal word terminates the loop and returns to executing from that word inclusively. Now look at how it is used in a definition and note that there are no special constructs needed, just the list, and then code.
pub LCDEMIT
    SWITCHES
      $0D LCDCR     $0A LCDLF   $0C LCDCLS
      $08 LCDBS     $09 LCDTAB  $15 LCDON
      $16 LCDOFF    $04 LCDHIDE
    SWITCH@ LCDCHAR
    ;
 
Now there are only 2 memory words required for every condition rather than 5 words originally that was trimmed down to 3 or 4 words. Faster and more compact!  

No comments:

Post a Comment