lua-users home
lua-l archive

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


David Given <dg <at> cowlark.com> writes:

> > I thought coroutines were entirely the right construct for state machines.
> 
> Depends on the state machine.
> 
> For example (this is a classic example by David Tribble, not my own):
> 
> int parse()
> {
>     Token   tok;
> 
> reading:
>     tok = gettoken();
>     if (tok == END)
>         return ACCEPT;
> shifting:
>     if (shift(tok))
>         goto reading;
> reducing:
>     if (reduce(tok))
>         goto shifting;
>     return ERROR;
> }

That code can be translated fairly directly into Lua using tailcalls:

  function parse ()
  
    local tok, reading, shifting, reducing
  
    reading = function ()
      tok = gettoken()
      if tok == END then return ACCEPT end
      return shifting()
    end
    
    shifting = function ()
      if shift(tok) then return reading() end
      return reducing()
    end
    
    reducing = function ()
      if reduce(tok) then return shifting() end
      return ERROR
    end
    
    return reading()
    
  end
    
As Rici said, whether the code is correct or good is another matter.  ;)