Metatables क्या हैं
एक metatable special rules की एक table है जो एक दूसरी table के behave करने का तरीका बदल देती है।
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- यह भूल जाना कि setmetatable table return करता है
- metamethod names इसकी metatable की बजाय table में ही रखना
- यह मान लेना कि 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: