Best way to handle "global variables" across multiple files?

Hey all, sorry if this is a little basic, but I'm working on separating my code -- which was all in main.lua -- into multiple files for different object classes etc. In general I'm trying to keep the files as self-contained as possible and have them all the game logic handled by main.lua, however I've run into instances where it makes sense for these class files to be aware of the state of things outside their class.

For example, I'm working on a soccer game and I want the player class (in the player.lua file) to be aware of the ball position. I suppose I could have the update loop in main.lua send the new position to every player every frame, but logically I feel it would make more sense for the players to "watch" the ball position themselves. One option would be to just make the ball position a global variable, but I know global variables can be a risky business.

I do have the ball object as its own class (in the ball.lua file) so I could import it into the player class, but I'm unsure the best way to do that. Would I import ball.lua into main.lua? Or directly into player.lua? What if they both need to access it? Or is there a better programming pattern for monitoring variables like this?

Any help is greatly appreciated!

Hi, what I usually do in these cases is create a state object for the current context that holds all relevant information that needs to be accessed by multiple classes. When a class gets instantiated I pass the state object for later access. The benefit of this approach is that, to take your example, the ball object doesn’t have to be instantiated before the players as long as it’s added to the state object before the players need to access it, e.g. when their update method is called.

As for whether the state should be a global variable my personal view is that it’s fine to make the global state global but local states should be local to their context. In that setup the global state object would contain data like the currently active view/screen/… or the active player if your game has multiple accounts whereas the local states would contain data that is only relevant in specific situations like the ball when it’s actually on screen.


Ah that makes so much sense! And I reckon I could use it for other things, like storing the positions of all the other players etc.