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.