伪交换机状态机

我正在尝试使用lua的“伪开关”来设置状态机,但是我遇到了一些问题。假设状态机应该检测几个颜色组合并返回特定的另一种颜色。(只是为了展示原理的一个例子)

始终有一个“旧”的状态和一个“新”的状态。

local state = {{},{}}
state["red"]["blue"] = function()
   stop_a_timer()
   return "purple"
end
state["blue"]["green"] = function()
   call_a_function()
   return "cyan"
end
state["green"]["red"] = function()
   call_another_function()
   return ("yellow")
end

function state_handler(old_state, new_state)
   if not (state[old_state][new_state]()) then
     return false
   end
end

到目前为止,检查多个值非常简单,但我怎么检查一个“假”的值?

我如何设置一个状态:

(old_state == "green") and (new_state != "blue")

当然

state["green"][(not "blue")] = function () whatever end

不工作。

点赞
用户1560821
用户1560821

你可以发明自己的符号表示法。例如,"!blue"将代表除了蓝色之外的任何颜色:

state["green"]["!blue"] = function () whatever end

然后,state_handler 将会像这样:

function state_handler(old_state, new_state)
  for selector, fun in pairs(state[old_state]) do
    if selector == new_state then
      fun()
    end
    if selector:find "^!" and selector ~= ("!" .. new_state) then
      fun()
    end
  end
end

在这里仅支持我们的记号用于 new_state。如果您也想要用在 old_state 上,您需要调整此函数。

2015-01-20 11:51:09