متامتودهای عملگرها در لوا
سفارشیسازی عملگرها با __add، __eq، __lt، __tostring، __len و __call
عملگرهای سفارشی با متامتودها
متامتودها اجازه میدهند جدولهایتان با عملگرهای لوا (+، ==، <، ...) کار کنند!
عملگرهای حسابی
| متامتود | عملگر |
|---|---|
__add | + |
__sub | - |
__mul | * |
__div | / |
__mod | % |
__pow | ^ |
__unm | یکانی - |
مثال: بردار دوبعدی
local Vector = {}
Vector.__index = Vector
function Vector.new(x, y)
return setmetatable({x = x, y = y}, Vector)
end
Vector.__add = function(a, b)
return Vector.new(a.x + b.x, a.y + b.y)
end
Vector.__mul = function(a, scalar)
return Vector.new(a.x * scalar, a.y * scalar)
end
Vector.__tostring = function(v)
return "(" .. v.x .. ", " .. v.y .. ")"
end
local v1 = Vector.new(1, 2)
local v2 = Vector.new(3, 4)
print(v1 + v2) -- (4, 6)
print(v1 * 3) -- (3, 6)
عملگرهای مقایسهای
| متامتود | عملگر |
|---|---|
__eq | == |
__lt | < |
__le | <= |
local Money = {}
Money.__index = Money
function Money.new(amount)
return setmetatable({amount = amount}, Money)
end
Money.__eq = function(a, b)
return a.amount == b.amount
end
Money.__lt = function(a, b)
return a.amount < b.amount
end
Money.__add = function(a, b)
return Money.new(a.amount + b.amount)
end
Money.__tostring = function(m)
return m.amount .. " تومان"
end
local p1 = Money.new(1000)
local p2 = Money.new(1000)
local p3 = Money.new(500)
print(p1 == p2) -- true
print(p3 < p1) -- true
print(p1 + p3) -- 1500 تومان
__tostring — نمایش رشتهای
وقتی print یا tostring روی جدول صدا زده شود:
local point = setmetatable({x = 10, y = 20}, {
__tostring = function(p)
return "نقطه(" .. p.x .. ", " .. p.y .. ")"
end
})
print(point) -- نقطه(10, 20)
print(tostring(point)) -- همان
__len — عملگر طول
local box = setmetatable({items = {1, 2, 3}}, {
__len = function(b)
return #b.items
end
})
print(#box) -- 3
__call — جدول مثل تابع!
local counter = setmetatable({count = 0}, {
__call = function(self, increment)
self.count = self.count + (increment or 1)
return self.count
end
})
print(counter()) -- 1
print(counter()) -- 2
print(counter(10)) -- 12
جدول خلاصه متامتودها
| متامتود | موقعیت |
|---|---|
__index | خواندن کلید ناموجود |
__newindex | نوشتن کلید جدید |
__add, __sub, ... | عملگرهای حسابی |
__eq, __lt, __le | مقایسهها |
__tostring | تبدیل به رشته |
__len | عملگر # |
__call | فراخوانی مثل تابع |
__concat | عملگر الحاق .. |
این مبحث بخشی از دوره آموزش کامل لوا است.