Can someone explain this metatable detail (quick issue)

Can someone briefly explain to me what “Can also be set to a table, in which case that table will be indexed” means? I understand metatables, but I don’t know what exactly can also be set to a table. It’s kind of vague to me.

Either you do nothing (__index = nil), explicitly handle it (__index = function), or implicitly handle it by passing it over (__index = table).

When you pass a table to __index in the metatable, if the index is not found in the current table, it then checks in __index.

local function index(tab, index)
	return "Manually handling nil value for: ".. index
end

local otherTab = {}
local example1 = setmetatable({}, {__index = index})
local example2 = setmetatable({}, {__index = otherTab})

otherTab.someValue = "someValue from otherTab"

print(example1.someValue) -- Manually handling nil value for: someValue
print(example2.someValue) -- someValue from otherTab

If the index is not found, it continues up the chain (calls __index again).

6 Likes