Easy Inheritance & Modularity in Lua

Seeing many flash developers praising Lua-based SDKs like Corona and Gideros that allow us to create mobile games quickly, I couldn’t help trying them myself.

First thing I did was read up some Lua tutorials. The language seems pretty easy to grasp — everything is a table which looks like associative array or a Dictionary in AS3. Good. Until I got to the point where I want to apply/emulate OOP or write code in modular fashion. This is where things become confusing because code examples from Corona and Gideros show you how to shove everything in one big main.lua file. To add even more confusion, different Lua OOP examples show you how to emulate OOP in different ways. And there are things called metatable and metamethods.

After an hour reading the docs and wiki and doing some experiments. I found that it’s really not that hard. Here’s an example of inheritance in one big file.

If you compile and run the program, you should see this in the console:

BTW, if you’re on Mac, you should try a cool app called Code Runner. You can do quick experiments without complicated project setup. Just type your code and click run.

Coding in Code Runner

So, how do you separate SUV and Car from main.lua and put them in different .lua files in a package? Easy.

  • Create a directory for your package just like what you always do in AS3, mine is car.
  • Then move Car and SUV definitions from main.lua and put them in SUV.lua and Car.lua respectively.
  • Add return Car at the end of Car.lua & return SUV at the end of SUV.lua.
  • Declare require "car.Car" in SUV.lua to “import” the Car table
  • Import Car and SUV into the main lua

Here’s my directory (package) setup and the code:

Package

Download

Here’s the zip containing the example → inheritance_lua.zip

Also in this category ...