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

What is a meta-table, and why would you use it?

Asked by 4 years ago

So, i have heard a lot of people talking about meta-methods, and newproxy and stuff.

Why would you use it, and how do you use it? Thanks, for reading.

0
This is a very large subject that introduces OOP, and is generally too broad to simplify in a short time. I suggest searching existing posts within this website, or researching through different sources. Ziffixture 6913 — 4y
0
Okay then. maxpax2009 340 — 4y

1 answer

Log in to vote
1
Answered by
Elyzzia 1294 Moderation Voter
4 years ago
Edited 4 years ago

a metatable allows you to specify special behavior when you do different things to a table with metamethods

a metamethod is just a function that runs when you do that thing to the table

for example, __index is a metamethod that runs whenever you index a table with a nonexistent key

local metatable = {}
metatable.__index = function(table, key) -- this has a table parameter since you can give multiple tables the same metatable
    return "The key " .. key .. " does not exist!"
end

local table = {}
setmetatable(table, metatable)

print(table.burger) --> The key burger does not exist!

you can also set __index to a table, in which case it will attempt to index that table instead

local fallbackTable = {}
fallbackTable.burger = "nom nom nom"
local metatable = {}
metatable.__index = fallbackTable
local table = {}
setmetatable(table, metatable)

print(table.burger) --> nom nom nom

there are a lot more metamethods, like __eq

local metatable = {}
metatable.__eq = function(a, b)
    if a.HasBlocks == b.HasBlocks then
        return true
    end
end

local roblox = {}
roblox.HasBlocks = true
roblox.Awesome = true
local minecraft = {}
minecraft.HasBlocks = true
minecraft.Awesome = false
setmetatable(roblox, metatable)
setmetatable(minecraft, metatable)

print(roblox == minecraft) -- true, even though roblox and minecraft are different tables

and also __tostring

local metatable = {}
metatable.__tostring = function(tbl)
    return "This burger is " .. tbl.Awesomeness * 100 .. "% awesome!"
end

local awesomeBurger = {}
awesomeBurger.Awesomeness = 0.6
setmetatable(awesomeBurger, metatable)

print(tostring(awesomeBurger)) --> This burger is 60% awesome!

you can find most metamethods and what they do here https://developer.roblox.com/en-us/articles/Metatables

while metatables aren't exclusively used for OOP, OOP is highly reliant on them, so it's good to familiarize yourself with them

Ad

Answer this question