Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What are Metatables for and how can they be used?

Asked by
Prestory 1395 Moderation Voter
6 years ago

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

0
They are sometimes used for stats (in game) BlackOrange3343 2676 — 6y
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.  Zafirua 1348 — 6y

2 answers

Log in to vote
5
Answered by 6 years ago
Edited 6 years ago

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.

Ad
Log in to vote
0
Answered by
Z_DC 104
6 years ago

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 :)

Answer this question