Metatables can be assigned to LUA tables to describe or change behaviour of operations on LUA tables. If table has metatable assigned, LUA engine looks for some special fields in metatables if some special events occurs. For example, if somebody wants to add two tables (system doesn't know how to add two tables because content is user dependent), LUA engine looks for special key __add in metatable to execute operator “+” and tries to execute funtion assigned to __add variable. In this case __add is a so called metamethod.
Possible LUA metamethods in metatable (see MetatableEvents):
By default LUA table has no metatable assigned.
local NormalTable = {} print(getmetatable(NormalTable)) -- will print "nil"
Metatables are normal LUA tables
local NormalTable = {} local MetaTable = {} setmetatable (NormalTable, MetaTable) print(getmetatable(NormalTable)) -- will print: table: 0x20db880
If mettables are normal table, so it is possible to use the same table also as metatable to save some resources
setmetatable (NormalTable, NormalTable)
setmetatable(table, metatable) returns its first argument, so it is possible to simplify code below:
local NormalTable = {} setmetatable (NormalTable, NormalTable)
to
local NormalTable = setmetatable ({}, {})
http://lua-users.org/wiki/MetatableEvents
http://lua-users.org/wiki/MetamethodsTutorial
To satisfy programmers and increase code readability function can be declared using colon “:” syntax
Usual way of declaring function:
function class.method(self, a, b, c) -- ... end
can be declared also as
function class:method(a, b, c) -- ... end
Function calls are also possible using both methods:
class:method(1, 2, 3) class.method(t, 1, 2, 3)