Minley
Minley

Reputation: 391

Fix not able to get variables declared from State:enter() in Statemachine

I am developing a game using lua and love 2D based on flappy bird. So I am using the StateMachine.lua to manage states and stuff, And have some states running all fine. I have a score state where I use params to get the data while changing the State and it works, but on a new state for coming back in game when unpaused, whatever I define in the enter method is not defined. And that is the method where I can access the params variable for the data. I commented everything and even defined arbitrary numbers in the enter method for testing purposes and rendering in render method, it returned nil. While if I define in the init method, it would work, here is my code without the commented code


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

In this, whenever I run this state, the text comes as nilnil. Also if I define some variables in the init method and change value in enter, it still won't do that. How can I overcome this problem and use the data passed through params and still be able to use that data in the file.

Here is the base state file if you need it

BaseState = Class{}

function BaseState:init() end
function BaseState:enter() end
function BaseState:exit() end
function BaseState:update(dt) end
function BaseState:render() end

Upvotes: 0

Views: 234

Answers (1)

Jason Goemaat
Jason Goemaat

Reputation: 29234

LUA doesn't have the concept of function overloading. Your second definition of PlayerStateP:enter():

function PlayStateP:enter()
    -- if we're coming from death, restart scrolling
    scrolling = true
end

Overwrites the first definition that takes params. If you call it with parameters, they are just being ignored. You need to choose different names for the functions.

Upvotes: 1

Related Questions