簡體   English   中英

使用 StateMachine 時 Love2D 中的零值錯誤

[英]Nil Value Error in Love2D while using StateMachine

我想使用“self.player:changeState()”調用“Entity:changeState”,但 function 沒有響應。 我已經使用評論突出顯示了問題,請通過它 go。 我嘗試調試問題,但在“self.player:changeState()”中線索消失了,我想知道為什么它不調用 function 並給我 nil 值。

注意:我在不同的文件中鍵入我的代碼(例如 - PlayState.lua)

使用 Debugger https://imgur.com/a/HmmnuPh 的截圖結果

-- PlayState.lua
-- Class library [https://github.com/vrld/hump/blob/master/class.lua][1]
PlayState = Class{}

function PlayState:init()
    self.background = math.random(3)

    self.player = Player({
        texture = 'green-alien',
        characterX = 10,
        characterY = 10,
        stateMachine = StateMachine {
            ['idle'] = function() return PlayerIdleState(self.player) end
        }
    })
    
    self.player:changeState('idle') --giving me error here
end
-- Player.lua
Player = Class{__includes = Entity}

function Player:init(def)
    Entity.init(self, def)
end

function Player:update(dt)
    Entity.update(self, dt)
end

function Player:render()
    Entity.render(self)
end


-- Entity.lua
Entity = Class{}

function Entity:init(def)
    self.characterX = def.characterX
    self.characterY = def.characterY
    self.texture = def.texture

    self.stateMachine = def.stateMachine -- [[Already checked by debugging here the argument 
                                            passed successfully refer screenshot]]

end

function Entity:changeState(state)
    self.stateMachine:change(state) -- The function that I want to call
end
-- StateMachine.lua
-- if everything goes well the value will end up here.
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:update(dt)
    self.current:update(dt)
end

function StateMachine:render()
    self.current:render()
end

這是我得到的錯誤

Error

src/states/game/PlayState.lua:15: attempt to call method 'changeState' (a nil value)


Traceback

src/states/game/PlayState.lua:15: in function 'init'
lib/class.lua:79: in function <lib/class.lua:77>
src/StateMachine.lua:17: in function 'change'
src/states/game/StartState.lua:13: in function 'update'
src/StateMachine.lua:22: in function 'update'
main.lua:45: in function 'update'
[C]: in function 'xpcall'

我從頭開始重寫了相同的代碼並且成功了。 也許問題出在字母的大寫上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM