【问题标题】:Writing function to check state's machine current state [Lua/Love2d]编写检查状态机当前状态的函数 [Lua/Love2d]
【发布时间】: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


【解决方案1】:

self.currentStateMachine:change 中设置为self.states[stateName]return

function StateMachine:change(stateName, enterParams)
    ...
    self.current = self.states[stateName]() -- note the () indicating the call

这意味着,除非返回值为self,否则self.current 将不等于在StateMachine:is 中与之比较的函数或对象self.states[stateName]

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

【讨论】:

  • 这实际上完美无缺。我在 StateMachine 中创建了一个 currentStateName,并在 StateMachine:change(...) 函数上将它传递给 stateName。澄清一下,在 self.states[stateName] 中存储了一个构造函数,它返回一个状态对象,因此,如果我理解正确,那么 self.current 指向由该构造函数创建的对象。这就是为什么我永远无法将它与 self.states[stateName]() 的另一个实例进行比较,因为我会在不同的地址接收另一个对象,因此,比较总是错误的。对吗?
【解决方案2】:

我有完全相同的问题 & 我想补充一下——也许一些 cmets 用我不明白的语言解释了这一点:D——但在我创建的 getCurrentState 函数中,我必须这样做:

function StateMachine:getCurrentState()
    variable = self.currentStateName
    return variable

其中 ofc 变量只是一些占位符。但我必须获取 self.currentStateName 指向的引用,否则比较总是失败。

【讨论】:

    猜你喜欢
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2011-07-07
    • 1970-01-01
    • 2016-01-10
    相关资源
    最近更新 更多