Jump tables

Sometimes we want to execute one of a large selection of words, depending on the outcome of a calculation. It is possible to set up a sequence of tests and branches (as introduced in Section7), however, FlashForth allows a neater solution in the form of a jump table. A word in FlashForth can be executed by feeding its execution token to the word execute. If you have a table of execution tokens, then you need only look up the one corresponding to a given index, fetch it and say execute. The following transcript shows such a jump-table for a collection of four functions, the word do-action to execute the appropriate word, given an index, and a sample of trials that shows the jump-table mechanism in action.
\ Set up the words that we want to selectively execute.
: ring  ( --) ." ring ring" ;  ok<#,ram>
: open  ( --) ." opening" ;  ok<#,ram>
: laugh ( --) ." ha ha" ;  ok<#,ram>
: cry   ( --) ." crying" ;   ok<#,ram>

\ Store the execution tokens in a table that allots into flash memory.
flash  ok<#,flash>
create actions ' ring , ' open , ' laugh , ' cry ,  ok<#,flash>
ram  ok<#,ram>

: do-action ( n --) 
  0 max 3 min 
  cells actions + @ execute ;  ok<#,ram>

\ Call up the actions.
3 do-action crying ok<#,ram>
0 do-action ring ring ok<#,ram>
2 do-action ha ha ok<#,ram>
5 do-action crying ok<#,ram>
The word ' (tick) finds the following name in the dictionary and puts its execution token (xt) on the stack. The word , (comma) compiles the xt into the table. Note that we are compiling these tokens into the flash memory of the microcontroller so that the jump table continues to work, even after a power break. In do-action, the words 0 max 3 min limit the incoming index value to the valid range for looking up a token in the jump-table. The token is fetched to TOS and then execute called. The final line of the transcript shows that the word cry is executed for the invalid index value of 5. You may want to handle incorrect input differently in your application.


The FlashForth distribution comes with a file (jmptbl.txt, AppendixC) that provides set of words for building jump tables. With these words, we can build a second jump table with a neater notation.

flash
JUMP_TABLE do-action-2
  0 | ring
  1 | open
  2 | laugh 
  3 | cry
  default| cry
ram
This gives essentially the same behaviour.
\ Call up the actions.  ok<$,ram>
3 do-action-2 crying ok<$,ram>
0 do-action-2 ring ring ok<$,ram>
2 do-action-2 ha ha ok<$,ram>
5 do-action-2 crying ok<$,ram>
Although not evident in this example, JUMP_TABLE allows more general key values than we could use in the basic array implementation for do-action. We could, for example, build a jump table with a selection of character codes as the keys.


Peter Jacobs 2013-06-12