Lua Metamethod __index
The __index metamethod supplies a value for a missing key. It runs only when a table lookup finds no value for that key.
A fallback table supplies missing values
An item holds only a name. Its fallback table supplies a color and a size.
local defaults = {color = "red", size = 3}
local item = {name = "box"}
setmetatable(item, {__index = defaults})
print(item.name, item.color, item.size)A fallback function computes a missing value
An item holds only a value of seven. Its fallback function doubles that value for one special key.
local function lookup(t, k)
if k == "double" then
return t.value * 2
end
return nil
end
local item = {value = 7}
setmetatable(item, {__index = lookup})
print(item.double, item.value)A key missing everywhere gives nil
A key absent from both the table and its fallback has no value. The lookup returns nil for that key.
local defaults = {color = "red"}
local item = {name = "box"}
setmetatable(item, {__index = defaults})
print(item.missing)
print(item.missing == nil)Example
local defaults = {theme = "light", lang = "en", volume = 5}
local user = {theme = "dark"}
setmetatable(user, {__index = defaults})
print(user.theme, user.lang, user.volume)Key points
- Missing key: a key with no value stored in the table itself.
- Fallback table: a table stored as __index supplies values for missing keys.
- Fallback function: a function stored as __index is called with the table and the missing key.
- Stored value: a value stored in the table itself always wins over a fallback value.
- Return value: the result of the fallback becomes the result of the lookup.
In this example, a defaults table holds three settings. A user table holds only a theme of dark. The stored theme wins, and the missing language and volume come from the defaults table.
Note
a fallback lookup does not store the value in the table itself.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A table holds theme dark and its fallback table holds theme light and lang en. What does the table give for theme and lang?