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

और भी Metamethods

__newindex, __call, और __len आपको writes guard करने, tables को functions की तरह call करने, और # बदलने देते हैं।

In this page:

  1. और Metamethods

और Metamethods

__newindex तब चलता है जब आप एक absent key को assign करते हैं, जो read-only tables या tracking allow करता है। __call एक table को function की तरह call होने देता है, और __len # operator का result बदलता है। rawset और rawget metamethods bypass करते हुए एक table पढ़ते और लिखते हैं।

Note: __newindex के अंदर rawset इस्तेमाल करें, नहीं तो assignment __newindex को फिर से हमेशा के लिए trigger करता है।

उदाहरण: More metamethods

lua
local log = {}
local t = setmetatable({}, {
  __newindex = function(tbl, k, v)
    log[#log + 1] = k
    rawset(tbl, k, v)
  end,
  __call = function(self, a, b) return a + b end,
  __len = function() return 42 end,
})
t.x = 1
t.x = 2
t.y = 3
print(table.concat(log, ","), t.x)
print(t(2, 3), #t)

local readonly = setmetatable({}, {
  __newindex = function() error("read-only table", 2) end
})
local ok, msg = pcall(function() readonly.a = 1 end)
print(ok, msg:match("read%-only table"))

-- Output:
-- x,y	2
-- 5	42
-- false	read-only table
{# 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. rawset के बिना __newindex के अंदर assign करना और हमेशा के लिए recurse करना
  2. यह उम्मीद करना कि __newindex उन keys के लिए fire होगा जो already exist करती हैं
  3. यह उम्मीद करना कि __len ipairs से इस्तेमाल होगा
चैप्टर सारांश
  • __newindex नई keys intercept करता है
  • __call tables को callable बनाता है
  • __len # override करता है
  • rawset recursion से बचाता है
🔒

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.