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

Classes और Methods

एक class shared methods की एक table है, और colon syntax object को self की तरह pass करता है।

In this page:

  1. Classes और Methods

Classes और Methods

Lua में कोई built-in class keyword नहीं है, इसलिए एक class एक table है जो methods hold करती है और __index के जरिए इसके instances के लिए metatable की तरह काम करती है। function Class:method() define करना function Class.method(self) के लिए sugar है, और obj:method() call करना obj को self की तरह pass करता है। Instances अपना data hold करते हैं और class से methods share करते हैं।

Note: obj:method(x) exactly obj.method(obj, x) है।

उदाहरण: Classes and methods

lua
local Dog = {}
Dog.__index = Dog

function Dog.new(name)
  return setmetatable({name = name}, Dog)
end

function Dog:speak()
  return self.name .. " says woof"
end

local d = Dog.new("Rex")
print(d:speak())
print(d.speak(d))
print(rawget(d, "speak"))

-- Output:
-- Rex says woof
-- Rex says woof
-- nil
{# 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. एक dot से एक method call करना और self भूल जाना
  2. एक colon से एक method define करना और यह भूल जाना कि self implicit है
  3. class की बजाय instance पर __index set करना
चैप्टर सारांश
  • एक class methods की एक table है
  • Class.__index = Class से methods link होते हैं
  • obj:method() self pass करता है
  • Instances methods share करते हैं
🔒

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.