The __index metamethod
__index tells Lua where to look when a key is missing from a table.
In this page:
The __index metamethod
When you read a key that is absent, Lua checks the metatable's __index field. If it is a table, the lookup continues there, and if it is a function it is called with the table and the key. This is used for default values, inheritance and computed fields. rawget bypasses __index.
Note:
Chains of __index tables are searched in order, which is the basis of inheritance.
Example: The __index metamethod
local defaults = {color = "red", size = 10}
local obj = setmetatable({size = 20}, {__index = defaults})
print(obj.color, obj.size)
print(rawget(obj, "color"))
local computed = setmetatable({}, {
__index = function(t, k) return k .. "!" end
})
print(computed.hello, computed.lua)
-- Output:
-- red 20
-- nil
-- hello! lua!
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Expecting __index to run for keys that already exist
- Creating an infinite loop by making __index refer back to the same table lookup
- Forgetting that __index is on the metatable, not the table
Chapter Summary
- __index handles missing keys
- It can be a table or a function
- It provides defaults and inheritance
- rawget skips it
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: