What can Metatables be used for and how can they be used may someone explain to me further on how to use them?
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.
There are mathematic, relational and equivilance, table access and library defined metamethods. A list of metatable keys can be found here.
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.
table setmetatable(table, metatable)
setmetatable()
takes the the table and metatable as the parameters, and return the table passed as the first argument.
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.
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 :)