Easy Inheritance & Modularity in Lua

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

First thing I did was read up some Lua tutorials. The language seems pretty easy to grasp — ever­ything is a table which looks like associative array or a Dictio­nary 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 con­fusing because code exam­ples from Corona and Gideros show you how to shove ever­ything in one big main.lua file. To add even more con­fusion, different Lua OOP exam­ples 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 exam­ple of inheritance in one big file.

If you com­pile 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 Run­ner. You can do quick experiments without com­plicated 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 pac­kage? Easy.

  • Create a directory for your pac­kage 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 (pac­kage) setup and the code:

Pac­kage

Download

Here’s the zip con­taining the exam­ple → inheritance_lua.zip

Also in this category …


Tags:

Comments are closed.