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

Constructors और Instance State

एक constructor function एक object बनाता है और हर instance को अपना data देता है।

Constructors और Instance State

एक constructor आमतौर पर new नाम का एक function है जो एक table बनाता है, class metatable attach करता है और इसे return करता है। हर object अपने fields store करता है, इसलिए एक बदलना दूसरों पर असर नहीं डालता। खुद class में रखा data सारे instances से share होता है, और एक instance के जरिए assign करना एक private field बनाता है जो इसे shadow करता है।

Note: per-object data self पर store करें और constants या counters class पर।

उदाहरण: Constructors and instance state

lua
local Account = {count = 0}
Account.__index = Account

function Account.new(owner, balance)
  local self = setmetatable({}, Account)
  self.owner = owner
  self.balance = balance or 0
  Account.count = Account.count + 1
  return self
end

function Account:deposit(n) self.balance = self.balance + n end

local a, b = Account.new("Ann", 100), Account.new("Bob")
a:deposit(50)
print(a.balance, b.balance, Account.count)
a.count = 99
print(a.count, b.count)

-- Output:
-- 150	0	2
-- 99	2
{# 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. mutable per-object data class table में रखना
  2. new से object return करना भूल जाना
  3. यह उम्मीद करना कि एक instance पर assignment एक shared class field बदल देगी
चैप्टर सारांश
  • new instance बनाता और return करता है
  • Instance fields इसके लिए private हैं
  • Class fields shared हैं
  • एक instance पर assign करना एक class field shadow करता है
🔒

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.