The two most powerful metamethods in Lua are __index and __newindex. They intercept read and write access to tables, forming the foundation of Object-Oriented Programming and reactive data systems.
The __index Metamethod (Intercepting Reads)
When you attempt to read a key from a table, and that key DOES NOT EXIST:
- If the table has no metatable or no
__index, it returnsnil. - If
__indexis another Table, Lua searches that second table for the missing key. - If
__indexis a Function, Lua calls that function with(table, key)and returns the result.
-- Fallback table pattern:
local defaultPreferences = {
theme = "dark",
volume = 80,
subtitles = true
}
local userSettings = {
volume = 100 -- User overrides volume, but leaves theme & subtitles default
}
setmetatable(userSettings, { __index = defaultPreferences })
print(userSettings.volume) -- 100 (Found directly in userSettings)
print(userSettings.theme) -- "dark" (Missing in userSettings, fetched from defaults!)
print(userSettings.subtitles) -- true
The __newindex Metamethod (Intercepting Writes)
When you attempt to assign a value to a key that DOES NOT CURRENTLY EXIST in the table, Lua intercepts the write using __newindex:
local auditLog = {}
local target = {}
local mt = {
__newindex = function(t, key, value)
print(string.format("AUDIT: Adding new key '%s' with value '%s'", tostring(key), tostring(value)))
rawset(t, key, value) -- CRITICAL: Use rawset to avoid infinite recursive loop!
end
}
setmetatable(target, mt)
target.username = "Alice" -- Triggers __newindex!
target.username = "Bob" -- Does NOT trigger __newindex because 'username' already exists!
CRITICAL RULE: The rawset and rawget Primitives Inside a
__newindexfunction, doingt[key] = valuewould re-trigger__newindex, creating an infinite recursive stack overflow. Always userawset(t, key, value)to set values directly bypassing metamethods, andrawget(t, key)to read values bypassing__index.
The Complete Proxy Pattern (State Tracking)
To intercept ALL reads and writes (even for keys that already exist), create an empty proxy table that delegates to an internal private data table:
local function createObservable(initialData)
local internalData = initialData or {}
local proxy = {}
local mt = {
__index = function(t, key)
print("OBSERVER: Read key -> " .. tostring(key))
return internalData[key]
end,
__newindex = function(t, key, value)
print(string.format("OBSERVER: Mutated key '%s' from '%s' to '%s'",
tostring(key), tostring(internalData[key]), tostring(value)))
internalData[key] = value
end
}
return setmetatable(proxy, mt)
end
local user = createObservable({ name = "Seraphina", level = 1 })
print(user.name) -- Triggers read interceptor
user.level = 2 -- Triggers write interceptor
user.guild = "Arcana" -- Triggers write interceptor
Exercises
- Build a proxy table that automatically validates data types upon write (e.g., throwing an error if someone assigns a string to a field designated as a number).
- Create an auto-vivifying table where accessing nested missing tables automatically creates them (
tree.a.b.c = 10). - Explain the difference between
table[key]andrawget(table, key).