और भी Metamethods
__newindex, __call, और __len आपको writes guard करने, tables को functions की तरह call करने, और # बदलने देते हैं।
In this page:
और 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
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
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- rawset के बिना __newindex के अंदर assign करना और हमेशा के लिए recurse करना
- यह उम्मीद करना कि __newindex उन keys के लिए fire होगा जो already exist करती हैं
- यह उम्मीद करना कि __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: