Continuing on the previous post, let’s talk about a neat method of implementing OOP with simple inheritance without using metatables in Corona. I have to say, the method is perfectly described in Darren Osadchuk’s post in his blog and this is where I have actually borrowed it from. It’s worth reading that post especially if you find metatables rather confusing or if you simply like simple solutions. Everything is clearly explained in the post so I will only describe here how exactly this method is utilized in Spellbind.
As it is mentioned in the post, Corona display objects (display groups included) are actually Lua tables. So what I did, following Darren’s method, is to create a class for each screen of my game. Screen classes share common functions like load(), start(), setup(), cleanup() and each one of them is essentially a display group which is created by the “mighty all-containing” load() function. This function creates and returns the screen display group along with all the visible objects and hotspots in it and also attaches other methods to it when is necessary. So in respect to my previous post, my global current screen variable holds an instance of such a class. So let’s say I want player to move to another screen. What I do is call the new screen’s load() method, show it using a – let’s say – fade-in transition effect in front of my previous screen and then, with a simple call on cleanup(), delete the previous screen from memory. My screen class behaves like an instance of a class. There is no inheritance involved here but as I’ve said before, having each screen in a different file and implemented as a class makes things easier for testing the game albeit at times I have to type more. But I can’t have everything, that’s for sure.
This is hardly the only place I use that method of class instancing in Spellbind. The inventory is a class implemented in the same way and it is basically a display group containing a table of inventory items. The same applies to the class that represents an inventory item and to classes that perform various game animations. In fact, all game objects are implemented that way. I feel it’s a rather simple solution without hassles. Pray spend some time and take a look on Darren’s post. Even though, as you may notice at the end of the post, the method breaks some strict OOP rules, it works so fine for me that I’m willing to be an object oriented design “outlaw” for a while.