尝试对本地变量 'params' 进行索引(值为 nil)

这是完整的错误信息

src/states/game/PlayState.lua:21: 尝试对本地变量 'params' 进行索引(值为 nil)

这是错误出现的代码,我们在这里调用 levelmaker.generate,具体是因为 params.levelwidth 产生了错误。

    function PlayState:enter(params)
    self.level = LevelMaker.generate(params.levelwidth or 100, 10, self.levelcount)
    self.tileMap = self.level.tileMap
    self.levelcount = 1 or params.level

    self.player = Player({
        x = 0, y = 0,
        width = 16, height = 20,
        texture = 'green-alien',
        stateMachine = StateMachine {
            ['idle'] = function() return PlayerIdleState(self.player) end,
            ['walking'] = function() return PlayerWalkingState(self.player) end,
            ['jump'] = function() return PlayerJumpState(self.player, self.gravityAmount) end,
            ['falling'] = function() return PlayerFallingState(self.player, self.gravityAmount) end
        },
        map = self.tileMap,
        level = self.level,
        score = params.score or 0
    })

    self:spawnEnemies()

    self.player:changeState('falling')
end

本函数从此处调用,也从此处传递参数:

function generatePole(width, flagPoleColor, Ypos, Xpos, part)
  return GameObject {
    texture = 'flags',
    x = (Xpos - 1) * TILE_SIZE,
    y = (Ypos - 1) * TILE_SIZE - 4,
    width = 6,
    height = 16,
    frame = flagPoleColor + part * FLAG_OFFSET,
    collidable = true,
    consumable = true,
    solid = false,

    onConsume = function(player, object)
        gSounds['pickup']:play()
        player.score = player.score + 250

        gStateMachine:change('play', {
            score = player.score,
            levelwidth = levelwidth + 10,
            level = levelcounter + 1
        })
    end
 }
end

这是我 State Machine 中写了 gstatemachine:change 函数的代码。

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

原文链接 https://stackoverflow.com/questions/70876310

点赞