lua-users home
lua-l archive

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


>From: romeo kalebic <romeo.kalebic@kron.hr>
>
>I'm learning lua with small fsm machine built in C and all actions are
>built in lua.
>FSM is described with: old_state, event, new_state and action.
>
>    state1, event1, state2, action1
>    state1, event2, state3, action2
>    etc..
>
>Now, I like to describe fsm in lua, maybe in lua table or ?.

One easy way would be to create a table in exactly the form above:

fsm=FSM{ 
{state1, event1, state2, action1},
{state1, event2, state3, action2},
...
}

where FSM is a function to be described soon.

Then, to run the machine, do
	local a=fsm[state][event]
	a.action()
	state=a.new

plus some error cheching if needed (eg, if a is nil, then the transition
(state,event) is invalid).
Also, you might want to do a.action(state,event,a.new) if the action can
use this info.

The function FSM takes the simple syntax above and creates tables for 
(state,event) pairs with fields (action,new):

function FSM(t)
 local a={}
 for i,v in t do
  local old,event,new,action=v[1],v[2],v[3],v[4]
  if a[old]==nil then a[old]={} end
  a[old][event]={new=new,action=action}
 end
 return a
end

(I'm using the new FOR for tables to be introduced in 4.0 :-)
 For the time being, use next or foreach instead...)

Note that this scheme works for states and events of any type: number, string,
functions, tables, anything. Such is the power of associate arrays.

Have fun.
--lhf