How should I share variables between instances/classes?

Posted by tesselode on Game Development See other posts from Game Development or by tesselode
Published on 2012-09-26T05:07:42Z Indexed on 2012/09/26 9:53 UTC
Read the original article Hit count: 177

Filed under:

I'm making a game using LOVE, so everything is programmed in Lua. I've been experimenting with using classes and object orientation recently. I've found out that a nice system to use is having most of the game's code in different classes, and having a table of instances with all of the instances of any class in it. This way, I can go through every instance of every class and update and draw it by calling the same function.

There is a problem, though. Let's say I have an instance of a player with variables for health and recharge time of a weapon. I also have a master instance which is responsible for drawing the HUD. How can I tell the master instance what the player's health is? Bad solutions:

  • Assuming that the player instance will always have the same position in the table - that can be easily changed.
  • Using global variables. Global variables are evil.
  • Have the master instance outside of the instances table, and have the player set variables inside the master instance, which it then uses for HUD drawing. This is really bad because now I have to make a duplicate of every variable the master instance needs.

What is the proper, standard way of sharing variables between instances? Do I need to change the way I keep track of instances?

© Game Development or respective owner

Related posts about entity-system

Related posts about lua