NCL 509: Command Dispatch

In the previous lesson, we built jump tables that selected subroutines using numbers.

For example:

Selection Handler
0 :command_look
1 :command_take
2 :command_open
3 :command_quit

We could choose a handler by calculating its position in the table, then calling the destination stored there.

But numbers aren't always the most useful way to identify an operation.

Imagine asking someone to enter a command.

They might type:

LOOK

It would be rather less friendly to require:

0

And expect them to remember what every number means.

What if we could select a handler by its name instead?

From Numbers to Names

Back in NCL 409: Associative Arrays, we built collections that associated one value with another.

For example:

"ALICE" → 29

The first value was a key. The second was its associated value.

Nothing says that value must be an age, a score, or even a memory address.

It could be an execution destination.

Command Handler
"LOOK" :command_look
"TAKE" :command_take
"OPEN" :command_open
"QUIT" :command_quit

Now we have a different kind of association:

"LOOK" → :command_look

We already know how to find a value using a key.

And, thanks to the previous lesson, we know how to call an execution destination stored in memory.

All we need to do is combine them.

Building a Command Table

Let's store four commands beginning at $200.

Each entry contains two values:

Offset Field
0 Command
1 Handler destination

Our entries therefore have a stride of 2.

Address Value
$200 "LOOK"
$201 :command_look
$202 "TAKE"
$203 :command_take
$204 "OPEN"
$205 :command_open
$206 "QUIT"
$207 :command_quit

We can initialize the table directly:

#table 0x200
#count 4

S.MOVE $200 "LOOK"
MOVE $201 :command_look

S.MOVE $202 "TAKE"
MOVE $203 :command_take

S.MOVE $204 "OPEN"
MOVE $205 :command_open

S.MOVE $206 "QUIT"
MOVE $207 :command_quit

Unlike the associative array we built in 409, this table doesn't need a length header.

We know it contains exactly four entries.

We're also not going to add, remove, or rearrange commands while the program runs.

This is simply a fixed collection of command-handler pairs.

Finding a Handler

Suppose the user entered "OPEN".

We need to find the matching entry.

The search is almost identical to the one we used in 408.

Start with the first entry, compare its command with "OPEN", and move to the next entry if it doesn't match.

Index Command Match?
0 "LOOK" No
1 "TAKE" No
2 "OPEN" Yes

Once we've found the entry, its handler destination is one memory location after its command.

We don't need to know that "OPEN" is entry 2 in advance.

That's the point of using a key.

Searching the Table

We'll use these working values:

#command $010
#index $000
#address $001
#key [$001]
#handler [$001]

Two names, one operand

#key and #handler both refer to [$001].

While searching, $001 points to a command, so we use #key. Once we've found a match, we increment the address to point to its handler destination and use #handler.

The aliases don't change how memory is accessed. They just make our intentions clearer.

Assume #command already contains the command we're looking for.

Start at index 0:

MOVE #index 0

Calculate the address of the current entry:

:search
MUL #address #index 2
ADD #address #address #table

The alias #key now refers to that entry's command.

Compare it with the command we're looking for:

S.BEQ :found #key #command

If it doesn't match, move to the next entry:

INC #index
BLT :search #index #count

If we've inspected all four entries, the command wasn't found:

JUMP :unknown

Otherwise, execution reaches :found.

At that point, #address contains the memory address of the matching command.

The associated handler destination is one location later:

:found
INC #address

And we can call it:

CALL #handler

That's command dispatch.

We found an operation by name and transferred execution to its handler.

Why CALL instead of JUMP?

Our command handlers are subroutines that eventually execute RET.

CALL records where execution should return after the handler finishes.

JUMP doesn't.

An indirect call behaves just like an ordinary call, except that its destination comes from memory.

Making a Dispatcher

The search works, but we don't want to copy it everywhere a program needs to execute a command.

Let's turn it into a subroutine.

We'll give it a simple interface:

Direction Value Type
Argument Command String
Result None —

The caller pushes the command string.

The dispatcher removes it from the stack, searches the table, and calls the matching handler.

For now, our handlers take no arguments and return no values.

The Complete Dispatcher

#table 0x200
#count 4

#command $010

#index $000
#address $001
#key [$001]
#handler [$001]

:dispatch
S.POP #command

MOVE #index 0

:search
MUL #address #index 2
ADD #address #address #table

S.BEQ :found #key #command

INC #index
BLT :search #index #count

JUMP :unknown

:found
INC #address
CALL #handler
RET

:unknown
-- Handle an unrecognized command.
RET

The caller can now write:

S.MOVE $020 "OPEN"
PUSH $020
CALL :dispatch

The dispatcher searches for "OPEN", finds :command_open, and calls it.

When :command_open executes RET, control returns to the dispatcher.

The dispatcher then executes its own RET, returning to the original caller.

There are two calls and two returns:

When :command_open executes RET, execution resumes inside :dispatch, immediately after the indirect CALL.

The dispatcher then executes its own RET, returning to the original caller.

Each CALL has its own return destination on the call stack. Neither subroutine needs to remember where its caller came from.

The call stack handles both return destinations independently.

One shared interface

Every handler in this table follows the same interface: no arguments and no results.

That means the dispatcher doesn't need to know which handler it selected before calling it.

If one handler expected two stack arguments while another expected none, we'd need additional rules for preparing those calls.

The table selects a destination. It doesn't enforce an interface.

Unknown Commands

What happens if the user enters:

DANCE

Our search checks every entry and finds no match.

That's not an execution error.

It's an ordinary possibility that the dispatcher must handle.

In our example, the search reaches:

:unknown
-- Handle an unrecognized command.
RET

We could display a message such as:

Unknown command: DANCE

Or we could return a status value to the caller.

The important thing is that we don't attempt to call a destination that wasn't found.

This is the same distinction we made in 409: a missing key is different from an ordinary value.

Our dispatcher handles the missing key by taking a separate execution path.

An Old Idea

Command interpreters

Command interpreters have been doing variations of this for decades.

On older personal computers, users often interacted with the operating system by entering commands such as:

DIR
COPY
DEL

The command interpreter had to determine what operation the user requested and arrange for it to run.

Some commands were implemented inside the interpreter itself. Others launched separate programs.

The underlying implementation wasn't necessarily a table of execution destinations. Command interpreters have used comparisons, lookup tables, parsers, and other mechanisms.

But the central problem was the same:

Turn a command supplied by the user into an operation performed by the computer.

Our "LOOK", "TAKE", and "OPEN" commands also resemble the verb-based interfaces of early text adventure games.

Those games often needed to interpret more than just a verb:

TAKE KEY
OPEN DOOR

That requires identifying arguments as well as selecting an operation.

Our dispatcher is simpler. It recognizes one command and calls one handler.

Still, it's the beginning of the same idea.

Dividing Responsibilities

Notice that our program now has three distinct responsibilities.

The caller decides when a command should be processed.

The dispatcher decides which handler corresponds to that command.

The handler performs the operation.

For example, when the caller supplies "OPEN", the dispatcher searches the command table and finds the destination associated with that key.

It calls :command_open, which performs the operation and returns.

The dispatcher doesn't need to know how OPEN works. The handler doesn't need to know where the command came from.

That's the benefit of giving each piece of the program a clear responsibility.

Changing the Available Commands

Suppose we add a new operation:

"HELP" → :command_help

We don't need another branch in the dispatcher.

We add another entry to the table and update its count.

The search already knows how to inspect any entry with the same structure.

Likewise, if we change the implementation of :command_open, the dispatcher doesn't need to change.

It still calls the destination associated with "OPEN".

The table connects the name of an operation to its implementation without mixing the two together.

Dispatching More Than Once

So far, we've dispatched one command.

But a command interpreter usually needs to process many commands.

A command interpreter typically runs in a loop: receive a command, call the dispatcher, and wait for the next command.

Each invocation of :dispatch handles one command and returns. The surrounding program is responsible for obtaining commands and deciding when to stop.

This keeps the dispatcher independent of the input mechanism.

The dispatcher doesn't need to know where the command came from.

It might come from a keyboard, a menu, a file, or another part of the program.

As long as the caller provides a command string, the same dispatcher can process it.

And because the dispatcher is a subroutine, the caller can invoke it whenever another command becomes available.

Try It

Extend our command interpreter with a fifth command:

HELP

Its handler should be named:

:command_help

When called, it should display the available commands:

LOOK
TAKE
OPEN
QUIT
HELP

Use the existing command table and dispatcher.

You should not need to change the search algorithm.

What needs to change?

The command table has four entries, each occupying two memory locations.

The fifth entry begins at $208.

Remember that the dispatcher uses #count to determine how many entries to search.

What about the handler?

:command_help must follow the same interface as the other command handlers.

It takes no arguments and returns no values.

It should finish with RET.

You can use the display instructions from Level 200 to show the available commands.

Show me one solution

Add the new entry during table initialization:

S.MOVE $208 "HELP"
MOVE $209 :command_help

Update the count:

#count 5

Then implement the handler:

:command_help
D.TXT "LOOK\r\nTAKE\r\nOPEN\r\nQUIT\r\nHELP\r\n"
D.BLT
RET

The dispatcher itself remains unchanged.

It searches five entries instead of four and calls whichever handler matches.


We've now built a small command interpreter from mechanisms we already understood.

An associative array finds an execution destination using a command string.

An indirect CALL invokes the selected handler.

And the call stack brings execution back afterward.

Command dispatch lets a program select what to do by name, without putting every operation inside the selection code.

But so far, the dispatcher owns the table of available handlers.

What if we wanted to give another subroutine an execution destination and let that subroutine decide when to call it?

That's where we're going next, in NCL 510: Callbacks.