lua-users home
lua-l archive

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


Awesome, thanks.  I looked at that FSM page, but didn't immediately understand how to use it.  Thanks!

On Fri, Jul 18, 2008 at 11:13 AM, Jorge <xxopxe@gmail.com> wrote:
I implemented a kind-of asynchronous state machine too. I looked into
tail calls, but skipped on them due to asynchronous part and also
because i won't be the one defining the state machine and is easier to
explain how to do it using a explicit transition table.
I posted a question on this list a while ago, and based my solution on
code posted by Roberto (i think it was, can't find it now)


Initialize a state machine using:

local function FSM(t)
       local a = {}
       for _,v in ipairs(t) do
               local old, matches_event, new, action = "" v[2], v[3], v[4]
                       if a[old] == nil then a[old] = {} end
                       table.insert(a[old],{new = new, action = "" matches_event = matches_event})
               end
       return a
end

A sample state machine with two states and two possible transitions could be:

--{state, predicate, new state, action}
local fsm = FSM{
       {"ini", cond1,  "end",  action1 },
       {"ini", cond2,  "end",  action2 },
       {"end", nil,    nil,    nil     }
}

where cond* are functions that evaluate whether a event is met, and action* are functions to be run on transitions.


Then, to advance the machine a single step you could use (current_state should start as "ini"):

       local state=fsm[current_state]
       local a
       --search first transition that verifies event
       for _, l in ipairs(state) do
               if l.matches_event and l.matches_event(event) then
                       a=l
                       break
               end
       end
       if a.action then a.action() end
       current_state = a.new

Hope that helps,

Jorge