What can Metatables be used for and how can they be used may someone explain to me further on how to use them?
What are Metatables for and how can they be used?
2 answers
Introduction
Metatables allow you to extend the operations available to a table. You can't call a generic table, nor add it with another value, but you can add this functionality through metatables. Metatables contain metamethod fields, which are often assigned to a callback function.
Metamethod keys
There are mathematic, relational and equivilance, table access and library defined metamethods. A list of metatable keys can be found here.
Sample
local tab = {}
local mt = {
__add = function(leftOperand, rightOperand)
local sum = 0
for i, v in pairs(leftOperand) do
sum = sum + v
end
for i, v in pairs(rightOperand) do
sum = sum + v
end
return sum
end
}
setmetatable(tab, mt)
In the example above, we defined an __add metamethod, which is invoked when the addition operator is used on the table. The __add metamethod takes two parameters, the left and write operand. In this example we assume that both operands were tables containing numbers, and we get the sum of the elements in the table and increment it to our sum variable, and the return sum.
Setting the metatable of a table.
table setmetatable(table, metatable)
setmetatable() takes the the table and metatable as the parameters, and return the table passed as the first argument.
Getting the metatable of a table.
variant getmetatable(table)
getmetatable() takes the table you'd like to get the metatable of as the argument, and returns its metatable if it exists or if the __metatable field is defined, it'll return the value of that.
Uses
Metatables are also useful in OOP, one defines the __index metamethod which makes inheritance and makes member access easier.
While I won't sit here and explain to you what metatables are, you can go to these pages to understand their uses:
http://wiki.roblox.com/index.php/Metatable <-- What they are http://www.lua.org/pil/16.1.html <-- Object Oriented Programming https://www.lua.org/pil/13.html <-- Lua page on them
Hope it helps :)
This discussion is preserved as it was. New answers, comments, and votes are closed.

2 comments
They are sometimes used for stats (in game)
Super old question but metatables are useful for creating Classes in Object Oriented Programming. Lua is not an Object Oriented Language but Imperative Programming Language. Thus to be able to create a
Classin Lua, Metatables along with metamethods is essential. That is one purpose of metatables.