Inheritance क्या है
एक subclass metatables chain करके एक parent class reuse कर सकता है ताकि missing methods ऊपर की ओर lookup हों।
In this page:
Inheritance
Inherit करने के लिए, setmetatable(Child, {__index = Parent}) इस्तेमाल करते हुए subclass की metatable को __index के जरिए parent की ओर point करें। एक missing key फिर instance, child class, और अंत में parent में search होती है। Subclass methods override कर सकता है और Parent.method(self) से explicitly parent का version call कर सकता है।
Note:
child constructor में Parent.new(...) call करें, फिर metatable को child class में बदलें।
उदाहरण: Inheritance
local Animal = {}
Animal.__index = Animal
function Animal.new(name) return setmetatable({name = name}, Animal) end
function Animal:speak() return self.name .. " makes a sound" end
local Cat = setmetatable({}, {__index = Animal})
Cat.__index = Cat
function Cat.new(name)
local self = Animal.new(name)
return setmetatable(self, Cat)
end
function Cat:speak() return Animal.speak(self) .. ": meow" end
local c = Cat.new("Tom")
print(c:speak())
print(Animal.new("Generic"):speak())
-- Output:
-- Tom makes a sound: meow
-- Generic makes a sound
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- child का अपना __index set करना भूल जाना
- एक method override करना और ज़रूरत पड़ने पर parent version call करना भूल जाना
- metatables का एक cycle बनाना
चैप्टर सारांश
- __index से classes chain करें
- Children parent methods override करते हैं
- Extend करने के लिए Parent.method(self) call करें
- Lookup instance, child, parent जाता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: