__index Metamethod क्या है
__index Lua को बताता है कि जब एक table से एक key missing हो तो कहाँ देखें।
In this page:
__index Metamethod
जब आप एक absent key पढ़ते हैं, Lua metatable की __index field check करता है। अगर यह एक table है, lookup वहाँ जारी रहती है, और अगर यह एक function है इसे table और key के साथ call किया जाता है। यह default values, inheritance, और computed fields के लिए इस्तेमाल होता है। rawget __index को bypass करता है।
Note:
__index tables की chains order में search होती हैं, जो inheritance का आधार है।
उदाहरण: The __index metamethod
local defaults = {color = "red", size = 10}
local obj = setmetatable({size = 20}, {__index = defaults})
print(obj.color, obj.size)
print(rawget(obj, "color"))
local computed = setmetatable({}, {
__index = function(t, k) return k .. "!" end
})
print(computed.hello, computed.lua)
-- Output:
-- red 20
-- nil
-- hello! lua!
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- यह उम्मीद करना कि __index उन keys के लिए चलेगा जो already exist करती हैं
- __index को same table lookup पर वापस refer कराकर एक infinite loop बनाना
- यह भूल जाना कि __index metatable पर है, table पर नहीं
चैप्टर सारांश
- __index missing keys handle करता है
- यह एक table या function हो सकता है
- यह defaults और inheritance देता है
- rawget इसे skip करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: