0Pricing
Lua Academy · Lesson

Constructors and new()

Write constructor functions that create and initialize instances.

Constructor Responsibility

A constructor creates and initializes an instance. It receives initial values, validates them, sets defaults for missing fields, and returns the new instance. A well-designed constructor ensures every instance starts in a valid state.

local Player = {}
Player.__index = Player

function Player.new(name, hp, mp)
  assert(type(name)=="string" and name~="","need name")
  return setmetatable({
    name = name,
    hp   = hp or 100,
    mp   = mp or 50,
    alive = true,
    items = {},
  }, Player)
end

local p = Player.new("Hero")
print(p.name, p.hp, p.mp)  -- Hero  100  50

Fluent Constructor

A fluent constructor returns self from setter methods, enabling method chaining during construction. This is a builder pattern in Lua.

local Config = {}
Config.__index = Config

function Config.new()
  return setmetatable({_data={}}, Config)
end

function Config:set(k,v) self._data[k]=v; return self end
function Config:build() return self._data end

local cfg = Config.new()
  :set("host","localhost")
  :set("port",8080)
  :set("debug",true)
  :build()

print(cfg.host, cfg.port)

All lessons in this course

  1. Classes via Metatables
  2. Constructors and new()
  3. Instance Methods and self
  4. Encapsulation with Closures
← Back to Lua Academy