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

Metatables क्या हैं

एक metatable special rules की एक table है जो एक दूसरी table के behave करने का तरीका बदल देती है।

In this page:

  1. Metatables

Metatables

हर table की एक metatable हो सकती है, setmetatable(t, mt) से set होती है और getmetatable(t) से पढ़ी जाती है। Metatable metamethods hold करता है, वे fields जिनके नाम दो underscores से शुरू होते हैं, जैसे __index और __add। जब एक operation table के लिए defined न हो तो Lua इन्हें lookup करता है। setmetatable अपना पहला argument return करता है, इसलिए इसे एक expression में इस्तेमाल किया जा सकता है।

Note: Strings एक metatable share करती हैं जिसका __index string table है, यही वजह है कि s:upper() काम करता है।

उदाहरण: Metatables

lua
local t = {}
print(getmetatable(t))
local mt = {}
local same = setmetatable(t, mt)
print(same == t, getmetatable(t) == mt)
print(getmetatable("abc").__index == string)

-- Output:
-- nil
-- true	true
-- true
{# 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. यह भूल जाना कि setmetatable table return करता है
  2. metamethod names इसकी metatable की बजाय table में ही रखना
  3. यह मान लेना कि plain tables की default से metatables होती हैं
चैप्टर सारांश
  • setmetatable एक metatable attach करता है
  • getmetatable इसे पढ़ता है
  • Metamethods __ से शुरू होते हैं
  • Plain tables की कोई metatable नहीं होती
🔒

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.