Lua中使用状态机FSM简单例子

FSM 有限状态机:

一个有限状态机是一个设备,或者是一个设备模型,具有有限数量的状态,它可以在任何给定的时间根据输入进行操作,使得一个状态变换到另一个状态,或者是使一个输入或者一种行为的发生。一个有限状态机在任何瞬间只能处在一种状态。

进入动作
退出动作
更新动作

FsmMachine.lua

FsmMachine = {}

function FsmMachine:New()
    self.__index = self
    o = setmetatable({}, self)
    o.states = {}
    o.curState = nil
    return o
end

-- 添加状态
function FsmMachine:AddState(baseState)
    self.states[baseState.stateName] = baseState
end

-- 初始化默认状态
function FsmMachine:AddInitState(baseState)
    self.curState = baseState
end

-- 更新当前状态
function FsmMachine:Update()
    self.curState:OnUpdate()
end

-- 切换状态
function FsmMachine:Switch(stateName)
    if self.curState.stateName ~= stateName then
        self.curState:OnLeave()
        self.curState = self.states[stateName]
        self.curState:OnEnter()
    end
end

状态机基类
BaseState.lua

BaseState = {}

function BaseState:New(stateName)
    self.__index = self
    o = setmetatable({}, self)
    o.stateName = stateName
    return o
end

-- 进入状态
function BaseState:OnEnter()
end

-- 更新状态
function BaseState:OnUpdate()
end

-- 离开状态
function BaseState:OnLeave()
end

测试类
Main.lua

require("BaseState")
require("FsmMachine")
FsmMachineTest = {}

-----[状态A,覆盖BaseState方法]----------------
aState = BaseState:New("aState")

function  aState:OnEnter()
    print("aState:OnEnter()")
end

function  aState:OnUpdate()
    print("aState:OnUpdate()")
end

function  aState:OnLeave()
    print("aState:OnLeave()")
end

-----[状态B,覆盖BaseState方法]----------------
bState = BaseState:New("bState")

function  bState:OnEnter()
    print("bState:OnEnter()")
end

function  bState:OnUpdate()
    print("bState:OnUpdate()")
end

function  bState:OnLeave()
    print("bState:OnLeave()")
end

-----[测试状态机]-----------------------------
fsm = FsmMachine:New()
fsm:AddState(aState)
fsm:AddState(bState)
fsm:AddInitState(aState)

for i = 1, 10 do
    if i == 5 then
        fsm:Switch("bState")
    end
    fsm.curState:OnUpdate()
end

输出

aState:OnUpdate()
aState:OnUpdate()
aState:OnUpdate()
aState:OnUpdate()
aState:OnUpdate()
aState:OnLeave()
bState:OnEnter()
bState:OnUpdate()
bState:OnUpdate()
bState:OnUpdate()
bState:OnUpdate()
bState:OnUpdate()
posted @ 2017-12-28 14:59  kevin_绿豆芽  阅读(3133)  评论(0编辑  收藏  举报