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

What are metatables and how to use the?

I have seen metatables used in various scripts but I do not understand the purpose of using them over regular tables. I have read the roblox wiki on metatables and I did so some looking around, But I still did not get a good explanation. I kind of understand how to format them...

local T1 = {}
local Metatable_I_guess = {}

setmetatable(T1, Metatable_I_guess)

--Not sure how to use GetMetatable ¯\_(?)_/¯

But I do not understand what situation I would be in where It would be necessary for me to set up a metatable. The biggest question that I have is where to use them and why should I use them. The rest I can find out on my own...

2 comments

0

https://developer.roblox.com/ tells u everything

0

people should rely more on that site cuz devforum is very confusing at times

1 answer

Everything you can do with OOP, you can do without them. So even if you at this level don't know where they can be applied it shouldn't be a big issue, the main advantage is usually that OOP/metatables helps shorten code and make it more modular.

All the things in Roblox are made of objects, they have properties and functions. For example parts have Names (part.Name, which is a property) and you can destroy them (part:Destroy(), which is a function).

Now at one point in your developer life you decide to create your own form of object with it's own custom properties that Roblox doesn't offer. So for this you need to use tables, with their own properties.

Car = {
	Name = "Bentley",
	Type = "Four-Wheeled Motorcar",
}

-- etc.

That's all well and good, but what if you want to change the car's name or type? You can do this:

Car.Name = "Honda"
Car.Type = "Five-Wheeled Sedan"

But there's another way to do this, using module scripts and OOP, like so:

-- module script
local Cars = {}
Cars.__index = Cars

function Cars:new(name, type)
	local newCar = {}
	setmetatable(newCar, Cars) -- I'll expand on this crucial part

	newCar.Name = name
	newCar.Type = type

	return newCar
end

function Cars:changeName(name)
	self.Name = name
end

return Cars

-- normal script
local Cars = require(pathToModule)

local Honda = Cars:new("Honda", "Car")
print(Honda.Name)
Honda:changeName("Bentley")
print(Honda.Name)

When I did setmetatable(newCar, Cars), I told the computer that whatever functions I can do using Cars:XXX, will now apply to newCar. That's all it did, and it's the most important part here because without it, I cannot do Honda:changeName().

I hope the rest of the answer made sense.

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