Chapter II · Idioms & deeper language / Lesson 11 of 27

Metatables: __index

You'll learn: Use __index (table or function) for fallback lookup and single-inheritance chains.

Every table can have a *metatable*. When a key is missing on t, Lua consults t's metatable's __index. If __index is a table, lookup recurses there — that's how OO inheritance works. If __index is a function, it's called with (t, key) — that's how computed/lazy lookups work.

metatables-index.lua
Output idle
Hit Run to execute.
Try it: Toggle Bytecode and find the get_table op for rex.kingdom. It misses on rex and Dog and lands on Animal via two metatable hops.