Where do you use metatables in a Roblox games?

Hi i’m new to scripting, and I just learned about metatables. I want to know where I would use them when scripting a Roblox game.

I mostly use them to work with OOP (there is great resources out here)
But metatables comes handy when mastering their functionality.
For example, making “proxy” tables (so __newindex and __index) fires everytime I change or add stuff to a table. OR I can automatially bind it to Player Attributes for example


local PlayerDatas = {}

game.Players.PlayerAdded:Connect(function(plr)
   PlayerDatas[plr] = setmetatable({}, {
      __index = function(_, index)
         return plr:GetAttribute(index)
      end,
      __newindex = function(_, index, value)
         plr:SetAttribute(index, value)
      end
   })
end)
1 Like

nowhere. :cross_mark_button:
Ideally you should never ever use them.:fire:
I maybe can use them for plugins becouse those are already annoying to make and writing everything manually would be hell.
Metatables not only most of the time work poorly with autocompletion+static types but also significantly lower perfomance. :chart_decreasing:
Conclusion: do everything without metatables and avoid metatable OOP and use alternatives instead. :handshake:

just do it manually dude… and at least cache metatable and avoid closures.
You don’t need this nobody needed sugarcoat that lowers perfomance.
You should care if your game is capable to run at least 50 FPS on a 2018 phone otherwise you failed your task.
Nobody including you needs this complex for no reason syntax to be real.

1 Like

Never had a problems with them to be honest.

Never had a problem with that either, whats the problem to type cast the metatable (if it doesnt seem to work with autocompletion) in to something you need.
And with Luau optimizations, metatables are very performant. I dont get where did you get that ideas.

Internals yes, very performant.
Custom-defined? Do have a lot of overhead on a large scale.

Could I please get the articles or resources about it?
Maybe I am missing something out. But as long as I remember, metatables never made my game lag, I use them for simple tasks to save up some time.

Do benchmarking and index speeds.
Dirrect indexing will always be faster

Benchmark
0.00013701498974114657 - dirrect
0.0002753450185991824 - metatable
--!strict
--!optimize 2
local t:number = 0
local function Empty(str:string):()
end

local tbl = {hi=""}
local tb = setmetatable({},{
	__index = tbl
})

t=0
for i=1,20 do
	local a:number = os.clock()
	for i=1,9999 do
		Empty(tbl.hi::string)
	end
	t+=os.clock()-a
end
print(`dirrect: {t/20}`)
t=0
for i=1,20 do
	local a:number = os.clock()
	for i=1,9999 do
		Empty(tb.hi::string)
	end
	t+=os.clock()-a
end
print(`metatable: {t/20}`)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.