Lesson 34 of 55
10 mins readPython The __index & __newindex Metamethods
In Plain English
The `__index` metamethod provides fallback lookups when accessing missing keys in a table. The `__newindex` metamethod intercepts new key assignments for proxies, validations, or read-only tables.
Deep Dive: How It Works
__index as Table: If key `k` is missing from `t`, Lua searches in `meta.__index[k]` (the basis for Lua OOP).
__index as Function: `function(t, k)` computes or logs dynamic lookups.
__newindex: Invoked when assigning to a key that does not currently exist in `t`.
rawget / rawset: Bypass metatable metamethods for direct table reads and writes.
Core Rules to Remember

__index Powers OOP: Points to a prototype table to inherit default methods and fields.

rawget and rawset: Read or write table fields directly without triggering metamethods.
Live Interactive Example
Hit Run Code to see it liveDefault Values and Method Inheritance with __index
Python 3.12
1
2
3
4
5
6
7
8
9
Output Console
Click "Run Code" to view the rendered output.
How it works: custom_server had no port field, so Lua retrieved 8080 from defaults via __index.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Inherit Default Status with __index
Create `local proto = { role = "User", active = true }`.
Create `local user = { name = "Alice" }` with metatable `{ __index = proto }`.
Print `"User " .. user.name .. " Role: " .. user.role`.
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.