lua-users home
lua-l archive

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


On Wed, 13 Jan 2010, David Kastrup wrote:
> 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.

What I meant was how to represent the coupling between the instruction
pointer and the program state in the source code. You can represent each
state as a function so that state transitions are tailcalls.

For example, unifdef <http://dotat.at/prog/unifdef/> has a fairly
complicated state machine with 10 basic states and 9 basic kinds of line.
(Featureitis and a half-arsed parser make it more complicated than that.)
At the moment the core loop looks like this:

	void process(void) {
		Linetype lineval;

		for (;;) {
			lineval = parseline();
			trans_table[ifstate[depth]][lineval]();
		}
	}

If C supported tail calls, then I could implement each state as a
function, state transitions as tail calls, and nesting as a normal
function call. No need for a trans_table[], no process() loop, and no need
for an explicit ifstate[] array of nested states.

Tony.
-- 
f.anthony.n.finch  <dot@dotat.at>  http://dotat.at/
GERMAN BIGHT HUMBER: SOUTHWEST 5 TO 7. MODERATE OR ROUGH. SQUALLY SHOWERS.
MODERATE OR GOOD.