Metatable
This page needs some serious TLC, stat! Please help us by cleaning it, fixing it up, or sparing it some love.
(Reason: Not enough info, perhaps incorrect info) |
A metatable is an addition on to normal tables for adding metamethods, making classes as well as protecting functions.
Contents |
Setting and getting a metatable
You will use setMetatable and getMetatable to set and get metatables.
You use getMetatable(table) to get your metatable from a table. It will return the __metatable metafield in the table.
setMetatable(table, metatable) to set your table's metatable. It will error if the __metatable metafield is set.
However, if the table has a metatable with the metafield __metatable, it will error when you use setMetatable and return what it is set to when getMetatable is called.
Metamethods
A metamethod is a type of function which changes the default way a table acts. The table below demonstrates what each
one is called, and how each one is used.
Name | Description | Arguments passed |
__index | Used when table[variable] is called. | The variable. |
__newindex | Used like __index, but it is only called when the variable matches an empty space in the table. | The variable. |
__call | A metamethod to turn a table's name into a function, or whatever you want it to do. | Function, Tuple |
__metatable | Used for protecting metatables, called when getmetatable() is used on the table, setmetatable() just errors. | Nothing (as far as Unit158 knows) |
__mul | Used as an operator overloader for multiplication. | The two objects being "multiplied". |
__div | Used as an operator overloader for division. | The two objects being "divided". |
__sub | Used as an operator overloader for substraction. | The two objects being "subtracted". |
__add | Used as an operator overloader for addition. | The two objects being "added". |
__mod | Used as an operator overloader for modulo. | The two objects being "divided". |
__pow | Used as an operator overloader for exponentiation operation. | The two objects being exponentiated. |
__unm | I am not exactly sure how this one works, it is for negatives though. | The table being changed into a negative. |
__eq | __eq is an operator overloader for comparison. | The two objects being compared |
__lt | Less than. | The two objects being compared |
__le | Less than or equal to. | The objects being compared |
__concat | The objects being concatenated | The two objects being concatenated |
__len | The # operator. | The object having the operation performed on it. |
Examples