我正在尝试使用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
不起作用。
答案 0 :(得分:1)
您可以创建自己的表示法。例如。 "!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
,你也必须调整这个功能。