有限狀態機

lua-users home
wiki

本文提供在 Lua 中執行有限狀態機 (FSM) 的範例模式。

這最初在郵寄清單中被問及

 > From: romeo kalebic <romeo.kalebic@k...>
 >
 > 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 ?.

在 Lua 中執行此項目的簡單方法之一,就是在上方範例中建立一個資料表

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

其中 FSM 是稍後要說明的函數。

然後,要執行這個機器,在迴圈中執行類似下列動作

local a = fsm[state][event]
a.action()
state = a.new

若需要,可以再做一些錯誤檢查(例如,如果 anil,那麼轉換 (stateevent) 為無效)。另外,您可能想執行 a.action(state, event, a.new)},如果該動作可以使用這些資訊的話。

函數 FSM 會採用上面簡單的語法,並為 (stateevent) 使用含有欄位 (actionnew) 的資料表。

function FSM(t)
  local a = {}
  for _,v in ipairs(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

請注意,這種機制適用於各種型別的狀態和事件:數字、字串、函數、資料表和任何事物。關聯陣列就是有此能耐。

享受吧。 ——LuizHenriqueDeFigueiredo

執行版本


function action1()
 print("action1")
end

function action2()
 print("action2")
end


function FSM(t)
  local a = {}
  for _,v in ipairs(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

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

local a = fsm["state1"]["event1"]
a.action()
state = a.new

注意:以上程式碼與 Lua 5.0 和 5.1 相符。


最近異動 · 偏好設定
編輯 · 歷程
最後編輯于 2010 年 8 月 8 日下午 5:24 (GMT) (差異)