lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Wesley Smith <wesley.hoke@gmail.com> writes:

>> Tail calls are good for state machines.
>> ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-443.pdf
>
> I find coroutines more elegant.

Yup.  Nothing beats using the instruction pointer and dynamic state as
state variable.

In my early days, I had to write a terminal emulator running on a
graphics card, and it had to support escape sequences.  And there were
literally dozens of states in the middle of escape sequences with
various temporary data you could be in when passing control back to the
calling program.

It was an utter mess until I finally saw the light.  Reversal of
control.  The stuff then looked something like

main:
call getchar
cp '['-'@'
jnz noescape
call getchar
cp '['
jnz beep
call getnum
cp ','
jnz beep
push h
call getnum
cp ';'
pop b
jnz beep
...

You get the drift.  getnum in turn called getchar.  And getchar did
nothing much except switch a terminal-emulator internal stack with the
controlling application's stack, and return to the application.

And when the controlling application called the terminal emulator with a
new character, the stacks were interchanged again, and control returned
to the terminal emulator, with the return stack in the state where it
called getchar.

_That_ was the right way to program the "state machine" inside of the
terminal emulator.  Simple, extensible, easy to use and understand, with
the _magic_ part distilled into about a dozen lines of intricate code
rather than spread all the way through, and all of the numerous states
being anonymous, implicit and strictly confined to one place each in the
source code.

I don't think I ever missed multithreading when programming in various
higher or lower level languages: lots of complex issues arise with that.
But synchronous control flow switching was a nuisance to miss out on,
and subroutine call/return is not a substitute for it.  It's the essence
of object oriented programming for me to have object-local control flows
interacting by message passing.  So most of the languages that call
themselves "object oriented" don't deliver in the area I consider most
important as a programming technique for boiling complex systems down
into objects: local control flow.

Lua does.

And that allows using stack frames as implicit state variables, making
many state machine applications much more readable, maintainable and
extensible.

-- 
David Kastrup