Edit this page

herkforth branch tables

This stuff will change as I create more sophisticated ways of dealing with tables. But for now here's how you can make and use branch tables:

Straight branch tables

Brant tables are implemented as a bunch of branch instructions (not a list of addresses.) You create them by just calling the words (green), then calling fix-table. Pass the number of branches in the table to fix-table:

] word1 word2 word3 [ 3 fix-table

Probably you'll want a word that gives you the address for the branch table. Here's one way:

: my-table [ create ] word1 word2 word3 [ 3 fixtable

You might use this like so:

: do-something 4 * my-table + jump ;

So now 2 do-something would execute word3.

Lookup branch tables

These have more complete code, but I still plan to improve them.

With this code you can make a table of word/key pairs. You can call a word to search through the keys for a match, and execute it's corresponding word.

If the key is not found, the last word in the table is called and the key is passed to it. This functions as a default action. Do not put a value after the default.

If you are somehow sure that your key will always be found, you do not need to supply a default. (But only do this if you are absolutely sure, because if you don't supply a default, and search for a key that doesn't exist, it will likely crash.)

Example of use:

: my-default . $3f emit $3f emit ;
: my-ltable [ exe-table-start ] action1 [ $51 w, ] action2 [ $78 w, ] my-default [ exe-table-end
: main-loop key my-ltable exe-table-lookup main-loop ;

At some point I'll make it so you don't need the exe-table-lookup in there.

See Also

herkforth docs

herkforth

Edit this page · home ·