Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand metatable in Lua?

I have used Python, but now I'm learning Lua because of Torch. The word 'metatable' is really hard to understand for me. For example, is metatable a special kind of table? How does it change the behavior of table?

like image 921
Bruce Zhang Avatar asked Dec 14 '22 05:12

Bruce Zhang


1 Answers

A metatable is simply a table that is used to control the behavior of another table (or userdata, or other Lua value). A table is a metatable only because it is used as a metatable. That is, being a "metatable" is not a fundamental property of a table. There is no "create_metatable" function or anything. It's just the name we use for a table which is used to control other tables.

Certain operations on tables (or userdata) are specified to check the table's metatable first. If the table (or userdata) has a metatable, and that metatable has a certain key/value pair in it, then the operation will use that key/value pair to perform that operation instead of the normal logic.

Each operation which can be overridden by a metatable has a specific key name associated with it. So if you try to perform addition on a table, the system will look for the __add key in the metatable in order to access it.

The value in the pair is usually (though not always) a function. Such functions are generally called "metafunctions". The parameters it takes and the meaning of its return value is defined by the particular operation calling it. A few operations allow the value to be a table or something else.

In Lua, you assign a metatable to a table (but not userdata) with the setmetatable function. From C, you use the lua_setmetatable function to assign a table (or userdata) a metatable.

Metatables are particularly important for C code that exposes C objects as userdata. Raw userdata is just an opaque blob of bits; Lua defines very few legal operations that can be performed on them by default. But by assigning them a metatable, you can give the userdata more abilities through metafunctions.

Note that Lua values other than tables and userdata can have metatables. However, unlike tables and userdata, values of each Lua type all share the same metatable for that type. So all strings have the same metatable, all numbers have the same metatable, etc.

like image 150
Nicol Bolas Avatar answered Jan 02 '23 13:01

Nicol Bolas