← Back to Lua Course | Chapter 6: OOP with Metatables | Lesson 6 of 7

Operator Metamethods की जानकारी

__add, __eq, और __tostring जैसे metamethods आपके objects को operators और print के साथ काम करने देते हैं।

In this page:

  1. Operator Metamethods

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

lua
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)
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. __add से एक नया object return करना भूल जाना
  2. यह उम्मीद करना कि __eq एक number से compare करते वक्त call होगा
  3. __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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.