Operator Metamethods की जानकारी
__add, __eq, और __tostring जैसे metamethods आपके objects को operators और print के साथ काम करने देते हैं।
In this page:
Operator Metamethods
Arithmetic operators __add, __sub, __mul, __div, __mod, __pow, __unm, और __idiv में map होते हैं, और comparisons __eq, __lt, और __le में। __tostring control करता है कि tostring और print object कैसे दिखाते हैं, और __concat .. operator handle करता है। Lua पहले left operand का metamethod try करता है और फिर right वाला।
Note:
__eq सिर्फ तब चलता है जब दोनों operands tables हों और already same object न हों।
उदाहरण: Operator metamethods
local V = {}
V.__index = V
local function vec(x, y) return setmetatable({x = x, y = y}, V) end
V.__add = function(a, b) return vec(a.x + b.x, a.y + b.y) end
V.__eq = function(a, b) return a.x == b.x and a.y == b.y end
V.__lt = function(a, b) return a.x < b.x end
V.__tostring = function(v) return "(" .. v.x .. ", " .. v.y .. ")" end
V.__concat = function(a, b) return tostring(a) .. tostring(b) end
local p, q = vec(1, 2), vec(3, 4)
print(p + q)
print(p == vec(1, 2), p < q, p > q)
print(p .. q)
-- Output:
-- (4, 6)
-- true true false
-- (1, 2)(3, 4)
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- __add से एक नया object return करना भूल जाना
- यह उम्मीद करना कि __eq एक number से compare करते वक्त call होगा
- __tostring define न करना और एक address print करना
चैप्टर सारांश
- __add और इसके जैसे arithmetic overload करते हैं
- __eq __lt __le comparison overload करते हैं
- __tostring print customise करता है
- Left operand पहले try होता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: