The Inheritance Setup
Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 31 of 70.
So far, you've built classes where each object looks up methods in a single prototype table. But what if you want one class to build upon another? This is where inheritance comes in—a child class can access everything from a parent class while adding its own features.
The key insight is that a class table itself can have a metatable. When Lua can't find something in the child class, it looks in the child's metatable's __index—which points to the parent class.
-- Parent class
local Animal = {}
Animal.__index = Animal
function Animal:new()
local obj = {}
setmetatable(obj, Animal)
return obj
end
function Animal:breathe()
print("Breathing...")
endNow here's the inheritance setup. We create a child class and set its metatable to look at the parent:
-- Child class
local Dog = {}
Dog.__index = Dog
setmetatable(Dog, {__index = Animal})This single line—setmetatable(Dog, {__index = Animal})—creates the inheritance link. When a Dog instance calls a method not found in Dog, Lua checks Animal.
The lookup chain works like this: instance → Dog → Animal. Each step uses __index to find the next table to search. This lets child classes automatically inherit all parent methods without copying them.
Challenge
EasyLet's build your first inheritance hierarchy! You'll create a simple parent-child class relationship where a Machine class serves as the base, and a Robot class inherits from it.
You'll organize your code across three files:
Machine.lua: Define your parent class with the standard class pattern. Include a:new()constructor and a:status()method that printsMachine is operational. Don't forget to set up__indexand return the class at the end of the file.Robot.lua: Define your child class that inherits from Machine. Require the Machine module, set up the Robot table with its own__index, and establish the inheritance link usingsetmetatable(Robot, {__index = Machine}). Include a:new()constructor that creates an instance with Robot as its metatable.main.lua: Bring everything together by requiring your Robot module, creating a Robot instance, and calling the inherited:status()method.
The key concept here is that your Robot class doesn't define :status() itself—it inherits this method from Machine through the metatable chain. When you call :status() on a Robot instance, Lua will look in Robot first, not find it, then follow the __index link to Machine where it discovers the method.
Your output should be:
Machine is operationalThis single line proves that inheritance is working—your Robot successfully accessed a method defined only in its parent class!
Cheat sheet
To create inheritance in Lua, set a class table's metatable to point to the parent class using __index:
-- Parent class
local Animal = {}
Animal.__index = Animal
function Animal:new()
local obj = {}
setmetatable(obj, Animal)
return obj
end
function Animal:breathe()
print("Breathing...")
end
-- Child class
local Dog = {}
Dog.__index = Dog
setmetatable(Dog, {__index = Animal})The inheritance link is created with setmetatable(Dog, {__index = Animal}). This allows Dog instances to access Animal methods automatically.
The lookup chain follows: instance → Child class → Parent class. Each step uses __index to find the next table to search.
Try it yourself
-- main.lua: Bring everything together
-- TODO: Require the Robot module
-- TODO: Create a Robot instance using Robot:new()
-- TODO: Call the inherited :status() method on your robot instance
-- This should print "Machine is operational"
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1The 'Self' Concept
Tables with FunctionsExplicit 'self'The Colon SyntaxDot vs ColonRecap - Moving Point4Project: Digital Bank
Project SetupDeposit Method7Polymorphism & Overriding
Overriding MethodsCalling Parent MethodsDuck TypingCommon InterfaceChecking TypeRecap - Employee Roles10Project: Shape Manager
Project SetupRectangle Class2Class Prototype Pattern
The Prototype ConceptLinking with __indexThe :new() ConstructorInitializing AttributesIndependent InstancesRecap - Car Factory5Operator Overloading in OOP
Adding ObjectsSubtracting ObjectsConcatenating ObjectsComparing Objects (<, >)Recap - Wallet Math8Encapsulation
Naming ConventionsClosures for PrivacyAccess via ClosuresRead-Only TablesValidation LogicRecap - Secure Vault11Design Patterns (Lite)
Factory FunctionsSingleton TableIterator PatternObserver (Listener)Recap - Logger Factory3Object State and Behavior
Instance VariablesGetter MethodsSetter MethodsCalculated PropertiesFormatting StringsEquality ChecksRecap - Student Grade6Inheritance Basics
The Inheritance SetupInheriting MethodsExtending the ConstructorAdding Child MethodsShared vs UniqueRecap - Shape Hierarchy