Lesson 41 of 55
9 mins readPython Data Encapsulation & Private Members
In Plain English
Because all table fields are public by default, Lua achieves true data encapsulation by returning an interface table of closures that close over private local state.
Deep Dive: How It Works
Closure-Based Objects: Instance data lives inside local variables (upvalues), not table fields.
Public Interface Table: The constructor returns a table containing only public getter/setter closures.
Immune to Tampering: External code cannot access or modify private variables directly.
Core Rules to Remember

Closure Privacy: Guarantees that private state cannot be accessed from outside.

No Self Parameter Needed: Methods bind directly to upvalues without requiring `self`.
Live Interactive Example
Hit Run Code to see it liveTrue Private Encapsulation with Closures
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
Output Console
Click "Run Code" to view the rendered output.
How it works: balance is private inside the closure and cannot be inspected directly as a table field.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Build Private Counter Object
Define `local function make_secret_counter() local val = 0 return { inc = function() val = val + 1 return val end } end`.
Instantiate `local c = make_secret_counter()` and print `"Count: " .. c.inc()`.
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.