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

Constructors and instance state

A constructor function creates an object and gives each instance its own data.

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

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
  1. Putting mutable per-object data in the class table
  2. Forgetting to return the object from new
  3. 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:

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.