Lua
Metatables and OOP
Implement OOP and operator overloading via metatables.
By EZ4Code Team
metatableoopoperator
Code
-- Vector class via metatable
local Vector = {}
Vector.__index = Vector -- lookups fall through to Vector
function Vector.new(x, y)
local self = setmetatable({}, Vector)
self.x = x or 0
self.y = y or 0
return self
end
-- Operator overloading
function Vector.__add(a, b)
return Vector.new(a.x + b.x, a.y + b.y)
end
function Vector.__tostring(self)
return string.format("(%d, %d)", self.x, self.y)
end
-- Method
function Vector:length()
return math.sqrt(self.x^2 + self.y^2)
end
-- Usage
local v1 = Vector.new(3, 4)
local v2 = Vector.new(1, 2)
local v3 = v1 + v2 -- (4, 6)
print(v3) -- (4, 6) (uses __tostring)
print(v3:length()) -- 7.21
print(getmetatable(v1)) -- Vector tableExplanation
Metatables hook into Lua's operations (add, index, call, etc.). __index makes inheritance work — when a key isn't found in the table, Lua looks in __index. setmetatable returns the table so you can chain. __add, __sub, __eq overload operators. __tostring controls print output. This is how all Lua OOP libraries work.
More Lua Snippets
Tables (Arrays and Maps)
Tables are Lua's only data structure — used as arrays and maps.
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.
OOP with Inheritance
Implement class inheritance using metatables.