# Word tables

The /lib/wordtbl.fs unit allows the creation of word tables allowing those words
to be called by their index. Example:

    wordtbl[
    :> 42 . ;
    ' anotherword
    :> 54 . ;
    ]wordtbl mytbl

    mytbl 2 wexec \ prints 54
    : foo mytbl 1 wexec, ;
    foo \ calls "anotherword"

What we call a "word table" is a structure where the first cell contains the
table's length (in number of elements) followed by that many cells, containing a
pointer to a word.

The "wordtbl[" and "]wordtbl" pair work by looking at PS accumulation betweeen
the two calls and consider this a series of word references. That is why the "'"
word can be used without problem.

## Lookup tables

Building upon word tables are lookup tables. They're the same as a word table,
but following it is a list of the same length as the word table (without the
element count field, which is redundant) and with lookup values in it.

With such a structure, you can look up a value in the lookup list with something
like "idx" and thus get a word index, which you can then call from the word
list.

The lookup table is built in a way that is similar to word tables, but each
entry of the table accumulates two elements on PS: the lookup value, then the
word reference. Example:

    lookuptbl[
    'a' :> 42 . ;
    'b' ' anotherword
    'c' :> 54 . ;
    'd' over \ low-tech way to bind multiple values to the same word
    ]lookuptbl mytbl

    mytbl 'd' ?lexec . \ prints 54, then 1
    mytbl 'z' ?lexec . \ prints 0 and calls nothing

## API

wordtbl[ ( -- )
  Record current PS level for word table accumulation. This call cannot be
  nested.

]wordtbl ( ... "name" -- )
  Create a new word table named "name" and write elements accumulated since the
  previous "wordtbl[" call to that table.

wordrefs ( n "tbl" -- )
  If all you have are references to existing words (that is, that you're only
  going to use "'"), this word saves you some typing:

    3 wordrefs mytbl foo bar baz
    wordtbl[ ' foo ' bar ' baz ]wordtbl mytbl

  are the same thing.

lookuptbl[ ( -- )
  Alias to "wordtbl[".

]lookuptbl ( ... "name" -- )
  Creates a lookup table "name" and write accumulated pairs on PS to that table.

wtbl@ ( tbl idx -- w ) *Preserves A*
  Return address of word at index "idx" in "tbl". Aborts if idx is out of
  bounds.

wexec ( tbl idx -- ) *Preserves A*
  Execute word at index "idx" in "tbl". Aborts if idx is out of bounds.

wexec, ( tbl idx -- )
  Compile execution of word at index "idx" in "tbl". Aborts if idx is out of
  bounds.

?lexec ( tbl val -- f )
  Look up "val" in lookup table "tbl". If found, call "wexec" on the found index
  and yield f=1. Otherwise, f=0.

wordtbllen ( tbl -- len )
  Yields the number of elements in "tbl".
