← Back to Lua Course | Chapter 6: OOP with Metatables | Lesson 2 of 7

The __index metamethod

__index tells Lua where to look when a key is missing from a table.

In this page:

  1. The __index metamethod

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

lua
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!
Common Mistakes
  1. Expecting __index to run for keys that already exist
  2. Creating an infinite loop by making __index refer back to the same table lookup
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.