What does setmetatable do?

I’ve seen some people use setmetatable() in their code, but I don’t know what it does. I’ve looked on the roblox developerhub but I still don’t understand why you would use it, how, and what it does.

Could somebody please answer my question?

setmetatable(x, m) sets x’s metatable to be m. There are tons of articles and such on metatables, doing a simple google search should yield more results.

(The wiki page has more info.)

A metatable gives a table extra behavior. Think of it like events for tables. For example, you can define custom behavior for when someone tries to use the addition operator (+) on a table. setmetatable is just a function that assigns a metatable to a table, like incapaz said. Here’s a quick example of how it can be used:

local myTable = {}
local myMetatable = {}

function myMetatable:__add(value)
	-- whatever this function returns is what `myTable + value` would evaluate to
	self[#self + 1] = value -- append the value to the end of `myTable`
	return self -- returning the table allows us to append multiple elements
	-- for example, (myTable + 4) will append `4` to myTable and evaluate to myTable.
	-- then, myTable + 4 + 5 is equivalent to myTable + 5, so that 5 gets appended
	-- then myTable + 4 + 5 is equivalent to myTable ... and so on
end 

setmetatable(myTable, myMetatable)
local _ = myTable + 4 + 5 + 6 -- append 4, 5, and 6 to the table

for index, value in ipairs(myTable) do
	print(index .. ":", value) -- 1: 4 | 2: 5 | 3: 6
end
5 Likes