Globals and singleton
Posted: Mon Dec 06, 2021 12:50 pm
I'm prepping up the global structure of my game and I was wondering what would be the most optimal approach given the layout of code I would like to use. I have read a bit about how Lua handles Globals and they way require works, but I'm wouldn't mind some additional feedback. I feel like my approach could be better but not sure how yet. (Some background: I have experience in Python/C++ but not much with Lua).
To give an example, here is how my structure roughly looks like in main.lua:
Example of my script gamestate.lua:
Other "modules" are pretty much using the same logic: a global variable stores an object that serves as a singleton.
This is convenient for me to be able to reference each object via other script, kind of like a system.
So now I know I could store the reference to the global into a local variable inside each script to speed things up a bit, however I wonder if there is an even better approach ? I prefer to look into that now before having to refactor a lot of code later.
To give an example, here is how my structure roughly looks like in main.lua:
Code: Select all
NFS = require( "lib.nativefs" )
PATH = require( "lib.path.path" )
JSON = require( "lib.dkjson.dkjson" )
STRICT = require( "lib.luastrict.strict" )
require( "scripts.utils" )
require( "scripts.font" )
require( "scripts.music" )
require( "scripts.input" )
require( "scripts.splash" )
require( "scripts.gamestate" )
function love.load( Args )
FONT:Init()
MUSIC:Init()
SPLASH:Init()
end
function love.update( DeltaTime )
INPUT:Update( DeltaTime )
MUSIC:Update( DeltaTime )
GAME_STATE:Update( DeltaTime )
end
function love.draw()
GAME_STATE:Draw()
end
Code: Select all
GAME_STATE = {
StateList = {
"Splash",
"MainMenu",
"Map",
"World",
"Fight",
"PauseMenu",
"Credits"
},
CurrentState = "Splash",
----------------------------------------
GetCurrentState = function (self)
return self.CurrentState
end,
----------------------------------------
Update = function(self, DeltaTime)
if self.CurrentState == "Splash" then
SPLASH:Update( DeltaTime )
end
end,
----------------------------------------
Draw = function(self)
if self.CurrentState == "Splash" then
SPLASH:Draw()
end
end
}
This is convenient for me to be able to reference each object via other script, kind of like a system.
So now I know I could store the reference to the global into a local variable inside each script to speed things up a bit, however I wonder if there is an even better approach ? I prefer to look into that now before having to refactor a lot of code later.