Is there a possibility to program a kind of "state machine" via functions?

Q

Is there a possibility to program a kind of "state machine" via functions?

A

Like variables also functions are handled internally as tables. A function thus has a name and a value. This value can be changed during runtime and hence decide which function will be called next.

Example code:


if myfunc then
  myfunc()
else
  -- defining all subfunctions
  function my_state_init_done()
    ..
    myfunc = my_state_1
  end
  function my_state_1()
    ..
    myfunc = my_state_2
  end
  function my_state_2()
    ..
    myfunc = my_state_init_done
  end
  myfunc = my_state_init_done
end