Inheritance is a fundamental concept in object-oriented programming that Lua supports through its flexible table and metatable system. It allows objects to inherit properties and methods from other objects, promoting code reuse and hierarchical structure.
Lua doesn't have built-in class-based inheritance, but we can implement it using tables and metatables. Here's a simple example:
-- Base class
local Animal = {}
Animal.__index = Animal
function Animal:new(name)
local instance = setmetatable({}, Animal)
instance.name = name
return instance
end
function Animal:speak()
print("The animal makes a sound")
end
-- Derived class
local Dog = setmetatable({}, {__index = Animal})
Dog.__index = Dog
function Dog:new(name)
local instance = Animal:new(name)
return setmetatable(instance, Dog)
end
function Dog:speak()
print(self.name .. " barks!")
end
-- Usage
local myDog = Dog:new("Buddy")
myDog:speak() -- Output: Buddy barks!
Inheritance in Lua is achieved through the following mechanisms:
Lua's flexibility allows for multiple inheritance, though it requires careful implementation. Here's a basic example:
local function createClass(...)
local c = {}
local parents = {...}
setmetatable(c, {__index = function(t, k)
for i = 1, #parents do
local v = parents[i][k]
if v then return v end
end
end})
c.__index = c
function c:new(o)
o = o or {}
setmetatable(o, c)
return o
end
return c
end
-- Usage
local Named = {name = "Unknown"}
function Named:getName() return self.name end
local Aged = {age = 0}
function Aged:getAge() return self.age end
local Person = createClass(Named, Aged)
local p = Person:new{name = "Alice", age = 30}
print(p:getName()) -- Output: Alice
print(p:getAge()) -- Output: 30
To fully grasp inheritance in Lua, it's beneficial to understand these related concepts:
Mastering inheritance in Lua opens up powerful possibilities for creating structured, maintainable code. It's a key concept for developers looking to implement complex systems or game logic using Lua's flexible programming model.