Lesson 39 of 55
9 mins readPython Constructors & Instance Creation (Class:new)
In Plain English
The idiomatic constructor pattern in Lua defines a `Class:new(o)` method that takes an optional table `o`, sets its metatable to `self`, and returns the initialized instance.
Deep Dive: How It Works
Standard Constructor: `function Class:new(o) o = o or {}; setmetatable(o, self); self.__index = self; return o end`.
Default Values: Assign initial fields inside the constructor.
Instantiation: `local acc = BankAccount:new({ balance = 1000 })`.
Core Rules to Remember

Class:new() Constructor: Standard pattern for creating initialized instances in Lua.

self.__index = self: Ensures the instance can find class methods.
Live Interactive Example
Hit Run Code to see it liveBankAccount Class with Constructor and Methods
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Output Console
Click "Run Code" to view the rendered output.
How it works: acc1 and acc2 are independent instances created via BankAccount:new.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Build Server Node Class
Create a `Server` class with `new(self, name, port)`.
Add a method `endpoint(self)` returning `self.name .. ":" .. self.port`.
Instantiate `local s = Server:new("api.zen", 443)` and print `"Endpoint: " .. s:endpoint()`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.