[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: finite state machine in lua
- From: Sean Conner <sean@...>
- Date: Sun, 28 Apr 2019 16:32:59 -0400
It was thus said that the Great Srinivas Murthy once stated:
> Last discussion in this archive is very old hence wanted to check.
> I need to implement a finite-state-machine in lua. Please let me know if
> http://lua-users.org/wiki/FiniteStateMachine is still the right way to go
> if I should use some libs. If so which one.
>
> Thanks
Personally, I tend to use mutually recursive functions to handle state
machines in Lua. Since Lua has tall calls, stack overflows are not an
issue.
function state1(state)
local event = getevent(state)
if event == ACTION1 then
return state2(state)
elseif event == ACTION2 then
return state3(state)
else
return state1(state)
end
end
function state2(state)
local event = getevent(state)
if event == ACTION3 then
return state1(state)
elseif event == ACTION4 then
return state3(state)
else
return state2(state)
end
end
function state3(state)
local event = getevent(state)
if event == QUIT then
return -- this leaves the state machine entirely
elseif event == ACTION1 then
return state1(state)
elseif event == ACTION2 then
return state2(state)
else
return state3(state)
end
end
I've used this method to implement TFTP, using the same state machine for
client and server, but starting in a different state depending upon which
side it was.
-spc