lua-users home
lua-l archive

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




On Sun, Sep 2, 2012 at 5:57 PM, Justin Cormack <justin@specialbusservice.com> wrote:
On Sun, Sep 2, 2012 at 3:25 PM, Jan Lühr <lua@stephan.homeunix.net> wrote:
> Am 02.09.2012 um 16:20 schrieb Justin Cormack:
>
> Personally I like to define everything in an fsm as a function, so
> each state is a function. Because Lua has proper tail recursion you
> can just call the next state (in _javascript_ you have to use a
> trampoline). [...]

I would probably do something along these lines:

[...]
  states = {
    boot = function()
      -- [...]
      nextstate()
    end,
  }

NOTE:

For a proper tail-call, the example above won't work. To fix it, you have to change the line:
    nextstate()
to:
    return nextstate()

For details, see: http://www.lua.org/manual/5.1/manual.html#2.5.8, last paragraph of the section.

That said, I also tend to implement FSMs as sets of functions, although usually called from a separate loop, which does some common inter-state work (my common usecase is for parsers, so the loop reads some data from input and passes it to the next state).

Uhm, I've just realized that I made the exact same error as above yesterday night in a hobby project... must go and fix it quickly...

/Mateusz Czapliński.