修复无法从State:enter()中声明的变量中获取的问题

我正在使用Lua和love 2D基于flappy bird开发游戏。因此,我使用StateMachine.lua来管理状态等,并且有一些状态运行良好。我有一个得分状态,其中我使用params在改变状态时获取数据,它有效,但是在新的状态卸载游戏时,我在enter方法中定义的任何变量都没有定义。而那是我可以访问用于数据的params变量的方法。我评论了所有内容,甚至在enter方法中为测试目的定义了任意数字和渲染方法,它返回nil。 但是,如果在init方法中定义,则会起作用,这是我的代码,没有注释的代码


PlayStateP = Class{__includes = BaseState}

PIPE_SPEED = 60
PIPE_WIDTH = 70
PIPE_HEIGHT = math.random(270,290)

BIRD_WIDTH = 38
BIRD_HEIGHT = 24

vari = math.random(20,90)

function PlayStateP:init()
    self.num =213
end
function  PlayStateP:enter(params)
    self.bird = params.bird
    self.pipePairs = params.pipePairs
    self.score = params.score
    self.timer = params.timer
    self.lastY = params.lastY
    self.num= 3
end

function PlayStateP:render()

    love.graphics.setFont(flappyFont)
    love.graphics.print(tostring(self.pipePairs)..tostring(self.num2), 8, 8)
end

--[[
    Called when this state is transitioned to from another state.
]]
function PlayStateP:enter()
    -- if we're coming from death, restart scrolling
    scrolling = true
end

--[[
    Called when this state changes to another state.
]]
function PlayStateP:exit()
    -- stop scrolling for the death/score screen
    scrolling = false
end

在这个例子中,无论何时我运行这个状态,文本都以nilnil的形式出现。如果我在init方法中定义一些变量并在enter中更改值,它仍然不会这样做。 如何解决这个问题并使用通过params传递的数据,并仍然能够在文件中使用该数据。

如果您需要的话,这里是基本状态文件

BaseState = Class{}

function BaseState:init() end
function BaseState:enter() end
function BaseState:exit() end
function BaseState:update(dt) end
function BaseState:render() end
点赞
用户369792
用户369792

LUA没有函数重载的概念。您的PlayerStateP:enter()的第二个定义如下:

function PlayStateP:enter()
    -- 如果我们从死亡中恢复,则重新开始滚动
    scrolling = true
end

覆盖了接受params参数的第一个定义。如果您使用参数调用它,它们将被忽略。您需要为这些函数选择不同的名称。

2020-08-24 13:25:51