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

Inheritance क्या है

एक subclass metatables chain करके एक parent class reuse कर सकता है ताकि missing methods ऊपर की ओर lookup हों।

In this page:

  1. Inheritance

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

lua
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
{# 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. child का अपना __index set करना भूल जाना
  2. एक method override करना और ज़रूरत पड़ने पर parent version call करना भूल जाना
  3. 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:

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.