【发布时间】:2020-06-28 02:42:42
【问题描述】:
我正在学习使用 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 返回一个指向表的指针,因此永远不会匹配比较运算符另一侧的任何内容。
感谢您的帮助!
【问题讨论】:
-
您可以更改
StateMachine:change的实现,使其保存进入状态的名称。然后在需要时比较名称(字符串)。 -
@EgorSkriptunoff 我确实做到了,然后创建了一些辅助函数进行调试。非常感谢您的意见,这真的很有帮助!
标签: lua game-development love2d