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

__index Metamethod क्या है

__index Lua को बताता है कि जब एक table से एक key missing हो तो कहाँ देखें।

In this page:

  1. __index Metamethod

__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

lua
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!
{# 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. यह उम्मीद करना कि __index उन keys के लिए चलेगा जो already exist करती हैं
  2. __index को same table lookup पर वापस refer कराकर एक infinite loop बनाना
  3. यह भूल जाना कि __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:

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.