Lua metatable examples

Lua has exactly one data structure — tables. And it uses those to implement everything else.

This is how inheritance works in lua:

t1 = {a = 3} -- t1 is a table with one name-value pair.
t2 = {} -- t2 is an empty table.
setmetatable(t1, t2) -- t2 is t1's metatable.
t3 = {c = 5} -- t3 is just another table like t1.

t2.__index = t3 -- when a lookup fails in t1, t2 will look for a value
-- in t3.

print(t1.a)
print(t1.b)
print(t1.c)

And the output is here:
$ lua lua_fun.lua
3
nil
5

This page explains with more detail.

When I first read this stuff, I wondered why I I couldn’t just make the metatable t2 be the place where t1 goes when a lookup fails, rather than require t3 to hold the defaults. Then I realized that __index doesn’t necessarilly need to point to another table. It could also hold a function, like this:

-- Now, we'll change the way t2 handles failed lookups in t1 so that it always returns the key that was asked for.
t2.__index = function (t, k)
return k
end

print(t1.a)
print(t1.b)
print(t1.c)

And now we get:
3
b
c

It is actually possible to make t2 be the metatable:
-- What happens with this?
t2.__index = t2
t2.d = 6

print(t1.a)
print(t1.b)
print(t1.c)
print(t1.d)

The results:
3
nil
nil
6

In conclusion, lua is neat.