__index and __newindex
Intercept field reads and writes with __index and __newindex metamethods.
__index Recap
__index is triggered when Lua tries to read a key that doesn't exist in the table. It can be a table (prototype lookup) or a function (dynamic computation). This is the most-used metamethod in Lua — it powers inheritance, default values, and lazy initialization.
local defaults = {timeout=30, retries=3}
local config = setmetatable({timeout=60}, {__index=defaults})
print(config.timeout) -- 60 (own value)
print(config.retries) -- 3 (from defaults)
print(config.missing) -- nil (not in either)__newindex Triggered
__newindex is triggered when Lua tries to write a key that does not yet exist in the table. If the key already exists, the assignment happens directly without triggering __newindex.
local proxy = setmetatable({}, {
__newindex = function(t, k, v)
print("New key:", k, "=", v)
rawset(t, k, v) -- actually store it
end
})
proxy.x = 10 -- New key: x = 10
proxy.x = 20 -- no trigger! x already exists
print(proxy.x) -- 20All lessons in this course
- Introduction to Metatables
- __index and __newindex
- Arithmetic Metamethods
- __tostring and __len