Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What are Metatables for and how can they be used?

What can Metatables be used for and how can they be used may someone explain to me further on how to use them?

2 comments

0

They are sometimes used for stats (in game)

0

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 Class in Lua, Metatables along with metamethods is essential. That is one purpose of metatables. 

2 answers

✓ Accepted answer

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.