Lua's __index Metamethod: Lightweight Inheritance via Tables
Learn how Lua's __index metamethod lets tables delegate missing keys, enabling prototype‑style inheritance without copying methods.
21 Nov 2025, 10:13 UTC

The Problem: Sharing Behavior Without Copying
When you create many objects that share the same methods, copying those functions into each instance wastes memory and makes updates tedious. You need a way for objects to look up missing behavior elsewhere.
How __index Enables Delegation
In Lua, a metamethod is a function hooked to a table via setmetatable. The __index metamethod is consulted when a key is not found in the table. If you set __index to another table, Lua will delegate the lookup there, enabling prototype‑style inheritance without duplicating data.
Worked Example: Simple Prototype Class
-- Prototype table with shared methods
local Shape = {}
function Shape:area()
return 0
end
function Shape:describe()
return string.format('Shape: %s', self.name)
end
-- Create an instance
local circle = { name = 'circle' }
setmetatable(circle, { __index = Shape })
-- Use delegated methods
print(circle:area()) -- 0
print(circle:describe()) -- Shape: circle
Here circle has no area or describe fields, so Lua forwards the call to Shape via __index. Changing Shape updates all instances.
Trade-offs and Limitations
- Lookup cost: Each missing key triggers a metamethod call, adding a small overhead compared to direct table access.
- Shared state: If the prototype table holds mutable values, all instances see those changes, which can be unintuitive.
- No automatic constructor: You must manually set up the metatable for each object or wrap the pattern in a factory function.
Actionable Takeaway
Use __index when you need lightweight, reusable behavior across many tables. Keep the prototype table free of instance‑specific state, and consider a factory function to hide the metatable boilerplate. This gives you prototype‑style inheritance with minimal memory overhead.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.