Setmetatable (table, metatable)
Each value in Lua can be used with a metatable. This metatable is an original Lua table that defines the behavior of the original values under specific actions. You can change the behavior of the specified operation that owns the value of the metatable by setting some values in the metatable domain. For example, when a non-numeric value is an addition operation, Lua checks whether there is a function in the "__add" field in its metatable. If there is such a function, Lua calls this function to perform an addition.
We call the key in MetaTable the event, the value of which is called the Meta Method (Metamethod). In the last example, the event is "add" and the Meta method is the function that performs the addition operation.
You can use the Getmetatable function to query the metatable of any one value.
You can replace the metatable of the table with the Setmetatable function. You cannot change the metatable of any other type of value from Lua (using the debug library exception); You must use the C API to do this.
Each table and UserData have separate metatable (of course multiple tables and UserData can share an identical table for their metatable); all other types of values, each sharing a single metatable. So all the numbers together have only one metatable, all the strings are also, and so on.
A metatable can control an object to do mathematical operations, compare operations, join operations, take the length of the operation, remove the operation of the standard action, metatable can also define a function, so that UserData for garbage collection call it. For these operations, Lua associates it with a specified health that is called an event. When Lua needs to initiate one of these operations on a value, it checks to see if there are any corresponding events in the metatable in the value. If so, the value of the key name (the Meta method) will control how Lua does the operation.
The actions that metatable can control are listed below. Each operation is distinguished by the corresponding name. The key name for each operation is a string with the operation name prefixed with the two underscore ' __ '; For example, the key of the "add" operation is the string "__add". The semantics of these operations use a Lua function to describe how the interpreter performs more appropriately.
Setmetatable
Sets the metatable for the given table. (You are cannot change the metatable of the ' other types ' from Lua, only from C.) If metatable is nil, removes the metatable of the given table. If The original metatable has a "__metatable" field, raises an error.
This function returns table.