I recently starting exploring Lua and Love2D and so far I'm amazed by the ease and versatility of the framework! It's been a really fun journey so far
It didn't take long before I stumbled across the hump library and started playing with gamestate.lua, but I'm struggling to understand is how to scope my variables to a specific game state.
SITUATION
I have several states with menus (main menu, selection of number of players, level selection, etc.), with every menu implemented as a table. Next, I want to scope such menu to a game state and I would like to avoid manually destroying (for example by doing so on leaving a game state).
To me, the "right" solution seemed to be by doing something like self.menu = Menu:new(). I would expect this would scope menu to the specific game state, but that's not the case: the table instance "leaks" into another game state.
I've simplified my code to a bare minimum to demonstrate this behavior. But first, here's the output when running the code and switching from state1 to state2:
OUTPUT
Code: Select all
Entered state1
self.foobar.abc: xyz
Pushing into state2
Entered state2
self.foo: nil
self.foobar.abc: xyz
I have a hunch that it's due to how I instantiate Foobar, but having read the PIL on scoping in Lua didn't bring me closer to how I should structure my code.
SPECIFIC QUESTIONS
I appreciate any help to get me closer to understanding:
1. Why is this happening in Lua?
2. How should I structure my code to avoid this?
CODE
main.lua
Code: Select all
Gamestate = require "libs.hump.gamestate"
require("foobar")
local state1 = require("state1")
local state2 = require("state2")
function love.load()
Gamestate.registerEvents()
Gamestate.switch(state1)
end
function love.keypressed(key)
if (key == "tab" and Gamestate.current() ~= state2) then
print("\nPushing into state2")
return Gamestate.push(state2)
end
end
Code: Select all
Foobar = {}
function Foobar:new()
return self
end
function Foobar:set_property(property, value)
self[property] = value
end
function Foobar:get_property(property)
return self[property]
end
Code: Select all
state1 = {}
function state1:enter()
print("\nEntered state1")
self.foo = "foo"
self.foobar = Foobar:new()
self.foobar:set_property("abc", "xyz")
print("self.foobar.abc: " .. self.foobar:get_property("abc"))
end
function state1:resume()
print("\nResumed state1")
end
return state1
Code: Select all
state2 = {}
function state2:enter()
print("\nEntered state2")
self.foobar = Foobar:new()
print("self.foo: " .. tostring(self.foo))
print("self.foobar.abc: " .. self.foobar:get_property("abc"))
end
function state2:keypressed(key)
if (key == "tab") then
print("\nPopping out of state2")
return Gamestate.pop()
end
end
return state2