This might require a semi-full tutorial on metatables and metamethods
Metatables
A table can be the metatable of another table. Multiple tables can have the same metatable. A table's metatable itself can have a metatable. A table can even be its own metatable.
setmetatable(x, m) allows you to set m to be x's metatable. Returns x back.
getmetatable(x) allows you to retrieve the metatable of x. Nil will be returned if x has no metatable.
Small example
local x = {};
local m = {};
setmetatable(x, m);
Metatables would contain metamethods. These can be thought of as "events for tables".
Please note
This is not strictly true. I am only using it as an abstraction to show you how it works more or less.
Metamethods
When working with metatables you also need to understand metamethods.
Metatables would contain these metamethods. These can be thought of as "events for tables".
Please note
This is not strictly true. I am only using it as an abstraction to show you how it works more or less.
An example of a metamethod is __index. It is invoked when you index table x for a nonexistent field.
A tiny example of __index
local x, m = {}, {__index = {key = "value"}};
setmetatable(x, m);
print(x.key);
Lua first checks if x has key. If it does, produce the value. If it does not, look for a metatable. If no metatable, produce nil. If there is a metatable that has the __index field produce the value in the __index table. If no __index field, produce nil.
__index can also be set to a function. When it is a function, produce its return.
local m = {__index = function(t, k)
return "Key: " .. k;
end};
print(x.k);
What is self
First, remember that thing:method(x) is syntax sugar (a nicer way to write something) for thing.method(thing, x).
local thing = {};
function thing:method(x)
print(self);
end
function thing.method(self, x)
print(self);
end
x is just some parameter; it is not needed. self is implicit parameter when you use the : notation when you define a function. It doesn't have to be called self when you explicitly pass it; it is just convention to name it self.
Let's try calling the method function.
thing.method();
thing:method();
Please note that this does not cover everything about metatables and metamethods. I encourage you to do a google search on this. I do not have much time to write more. I will edit this answer with any more info later.