Lua
OOP with Inheritance
Implement class inheritance using metatables.
By EZ4Code Team
oopinheritanceclass
Code
-- Base class
local Animal = {}
Animal.__index = Animal
function Animal.new(name)
local self = setmetatable({}, Animal)
self.name = name
return self
end
function Animal:speak()
return self.name .. " makes a sound"
end
-- Derived class
local Dog = setmetatable({}, {__index = Animal})
Dog.__index = Dog
function Dog.new(name, breed)
local self = Animal.new(name) -- call parent constructor
setmetatable(self, Dog) -- override metatable
self.breed = breed
return self
end
function Dog:speak() -- override
return self.name .. " barks!"
end
function Dog:fetch()
return self.name .. " fetches the ball"
end
-- Usage
local a = Animal.new("Cat")
local d = Dog.new("Rex", "Labrador")
print(a:speak()) -- "Cat makes a sound"
print(d:speak()) -- "Rex barks!"
print(d:fetch()) -- "Rex fetches the ball"
-- Type check
print(getmetatable(d) == Dog) -- true
print(getmetatable(getmetatable(Dog).__index) == Animal) -- inheritance chainExplanation
Inheritance via chained metatables: setmetatable(Dog, {__index = Animal}) makes Dog lookups fall through to Animal. The derived constructor calls the parent constructor then reassigns the metatable. Methods are overridden by name. Use self (first param) — the : syntax sugar passes self automatically; obj:method() == obj.method(obj).
More Lua Snippets
Tables (Arrays and Maps)
Tables are Lua's only data structure — used as arrays and maps.
Metatables and OOP
Implement OOP and operator overloading via metatables.
Coroutines
Cooperative multitasking with coroutines.
Modules
Create reusable modules in Lua.
String Manipulation
Pattern matching and string functions in Lua.
File I/O
Read and write files in Lua.