Lesson 40 of 55
9 mins readPython Class Inheritance & Method Overriding
In Plain English
Inheritance in Lua is accomplished by making a subclass table delegate to its parent class via `setmetatable(Subclass, { __index = Superclass })`.
Deep Dive: How It Works
Subclass Declaration: `Subclass = Superclass:new()` creates a subclass table inheriting from `Superclass`.
Method Overriding: Redefining `function Subclass:method()` overrides the parent version for subclass instances.
Calling Super: Call parent method explicitly with `Superclass.method(self, ...)`.
Core Rules to Remember

Prototype Inheritance Chain: Instance -> Subclass -> Superclass lookup chain.

Method Overriding: Subclasses provide specialized implementations of base methods.
Live Interactive Example
Hit Run Code to see it liveInheritance Hierarchy in Lua
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Output Console
Click "Run Code" to view the rendered output.
How it works: Dog inherited Animal constructor and overrode the speak method.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Override Worker Method
Create `local Worker = {} Worker.__index = Worker function Worker:new(name) local o = {name=name} setmetatable(o, self) return o end function Worker:work() return self.name .. " is working" end`.
Create `local Dev = Worker:new() Dev.__index = Dev function Dev:work() return self.name .. " is coding Lua" end`.
Instantiate `local d = Dev:new("Alice")` and print(d:work()).
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.