Quick question on setmetatable

How are you able to return the setmetatable method? Isn’t it a built-in function?

Or does it work like this: it returns the table you’re setting the metatable to.

So like here, I’m returning the “new” variable because it makes sense to me, I’m returning an object

function stats.New()
	local new = {}
	setmetatable(new, stats)
	
	return new
end

If I did something like this, is it the same thing? Or am I thinking about this wrong

function stats.New()	
	return setmetatable({}, stats)
end

That’s the same thing, you’re using a variable for no reason though. But if you plan on adding to that variable then yeah it would work.

1 Like

Yeah, that’s why I asked this question in the first place. Thanks for the clarification

Okay just to make sure I’m doing this right. I could turn this:

function stats:Create(stat, numerical)
	if numerical then
		self[stat] = 0
		print("Created numerical value: ".. stat)
	else
		local newtable = {}
		setmetatable(newtable, stats)
		
		print("Created value: ".. stat)
		
		self[stat] = newtable	
	end
end

Into this, correct?

function stats:Create(stat, numerical)
	if numerical then
		self[stat] = 0
		print("Created numerical value: ".. stat)
	else		
		print("Created value: ".. stat)
		self[stat] = setmetatable({}, stats)
	end
end