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.
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