Constructors and instance state
A constructor function creates an object and gives each instance its own data.
In this page:
Constructors and instance state
A constructor is usually a function named new that builds a table, attaches the class metatable and returns it. Each object stores its own fields, so changing one does not affect others. Data placed in the class itself is shared by all instances, and assigning through an instance creates a private field that shadows it.
Note:
Store per-object data on self and constants or counters on the class.
Example: Constructors and instance state
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Putting mutable per-object data in the class table
- Forgetting to return the object from new
- Expecting assignment on an instance to change a shared class field
Chapter Summary
- new builds and returns the instance
- Instance fields are private to it
- Class fields are shared
- Assigning on an instance shadows a class field
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: