lua - 编写检查状态机当前状态的函数 [Lua/Love2d]
问题描述
我正在学习使用 LÖVE2D 和 Lua 进行游戏开发,最近我一直在使用状态机类。我自己没有编写课程代码,但我已经完成了代码,我想我几乎明白了,除了这个问题。
问题是,我正在尝试提示该类的当前状态,以便我可以在if中使用它,但无论如何,我都无法正确处理。
这是该类的相关代码:
StateMachine = Class{}
function StateMachine:init(states)
self.empty = {
render = function() end,
update = function() end,
enter = function() end,
exit = function() end
}
self.states = states or {} -- [name] -> [function that returns states]
self.current = self.empty
end
function StateMachine:change(stateName, enterParams)
assert(self.states[stateName]) -- state must exist!
self.current:exit()
self.current = self.states[stateName]()
self.current:enter(enterParams)
end
我基本上想做的是:
function StateMachine:is(stateName)
if self.current == self.states[stateName] then
-- this never executes
return true
end
return false
end
我尝试更改self.states[stateName]
为其他东西来测试它,还尝试将内容打印到控制台以查看为什么比较永远不会正确。它似乎self.current
返回一个指向表的指针,因此永远不会匹配比较运算符另一侧的任何内容。
谢谢你的帮助!
解决方案
self.current
设置为in的return
值self.states[stateName]
StateMachine:change
function StateMachine:change(stateName, enterParams)
...
self.current = self.states[stateName]() -- note the () indicating the call
这意味着,除非返回值为 ,否则self
将self.current
不等于self.states[stateName]
与之比较的函数或对象StateMachine:is
function StateMachine:is(stateName)
if self.current == self.states[stateName] then -- here we are comparing the function to the return value
我建议扩展您的状态对象以具有一个:getName
函数,该函数将返回stateName
或将名称存储在您StateMachine
的键下,例如currentStateName
.
推荐阅读
- rest - 如何使用 REST 在 Magento 中获取所有订单?
- ios - 在 iOS 设备上获取 HTTPOnly Cookie
- javascript - 根据javascript中的单选按钮选择更改变量值
- ios - Xamarin 形式:jamesmontemagno/MediaPlugin:在 IOS 应用程序中添加到 UI 时,所选图片正在旋转
- ios - 我无法解决错误“编码分类不符合键值编码的键”
- mysql - 适当地存储图像
- c++ - 在 C++ 中评估块语句的结果
- android - 任何人都可以知道如何在android中将图像数组发布到服务器吗?
- python - 无法安装 Mahotas python 库
- javascript - AngularJS 调用 WebMethod 并返回一个 JSON 字符串