首页 > 解决方案 > 编写检查状态机当前状态的函数 [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返回一个指向表的指针,因此永远不会匹配比较运算符另一侧的任何内容。

谢谢你的帮助!

标签: luagame-developmentlove2d

解决方案


self.current设置为in的returnself.states[stateName]StateMachine:change

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

这意味着,除非返回值为 ,否则selfself.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.


推荐阅读