Metatable Index

According to the wiki, the metamethod “__index” fires when an index in a table is read from if the value for that index is nil.

I don’t quite understand what “table” they mean. For example:

local mt = {"ya"}
mt.__index = mt

local t = {}
setmetatable(t,mt)
print(t[1])

According to their explanation, the “table” is “t”, correct? If that’s true, i’m guessing that “mt” being a metatable of “t” has something to do with mt’s metamethod __index being fired when t[1] is tried (t[1] is nil).

Can someone please clarify.

Think of a metatable as a table of events that occur when certain operations happen in relation to a table.
You can actually make a single table both a metatable and table. But in that instance yes mt is the table where you can intervene in operations that occur with table t.

Everything you stated is correct.

When you do t[1]:

  1. Lua checks it t[1] exists. If so, Lua returns it.
  2. Lua checks if t has a metatable (mt). If not, Lua returns nil.
  3. Lua checks if mt has an __index. If not, Lua returns nil.
  4. Lua checks if __index is a table. If so, Lua returns __index[1].
  5. Lua checks if __index is a function. If so, Lua returns __index(t, 1).

Your example will print "ya" because it hits step 4.

5 Likes

a good way to use it would be to store functions and etc that multiple objects of that class would use