Object Inheritance
03/02/21 08:15 Filed in: Lua
Last time I started investigating OOP in Lua and learned how to create objects, instances, and methods using tables and metatables. Today, I want to find how to handle inheritance in Lua.
First, A Problem
Before I dive into inheritance, I want to mention one problem with the objects. One issue with how objects are created is that if the object contains a table problems arise. This is due to the fact that tables are passed by reference instead of value so when we create an object with a table, we don't get a copy of the table, but a pointer to the table in our class definition. That is, we don't get an instance (copy) of the table, but the original table. The way to fix this is to create a copy the table and its properties by value in the constructor.
Here is my Vehicle class and constructor from last time. I've added a position table to the class in lines 10-13.
In the constructor's lines 21-23 I create an instance of an empty position table, and then copy the individual properties from the class into the new instance. I can see this being a pain if your class contains multiple tables with lots of properties. This is a good reminder to keep your classes as simple as possible.
Inheritance
In Lua, inheritance is implemented by creating a subclass by using the parent class's constructor. I'm going to create a subclass of the Vehicle class called Boat.
This looks like Boat is an instance of Vehicle, but it's actually a subclass. It shares all the characteristics of Vehicle, but has an additional property, sails. Now that I have a subclass, I can create instances of it.
rowboat is an instance of type Boat which is a subclass of Vehicle. It has no sails. sunfish is also of type Boat but has sails. Both boats have access to the properties: make, model, color, year, speed, and position of the Vehicle grandparent class.
Multiple Inheritance
That's it for inheritance, specifically single inheritance. Although multiple inheritance is possible, I try to avoid it so I won't go into it. Although inheritance useful, I'll only use it when needed and stick to the more functional nature of Lua.