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

Help with metamethod returning nil?

Hi! I've been trying to learn metatables so I thought I'd start off with something basic. The __add works fine, but for some reason, __sub doesn't.

local vec2_meta = {
	__add = function(a,b)
		return Vec2(
			a.x+b.x,
			a.y+b.y
		)
	end,
	__sub = function(a,b)
		return Vec2(
			a.x-b.x,
			a.y-b.y
		)
	end,
	
}

function Vec2(x,y)
	local v = {
		x = x or 0,
		y = y or 0
	}
	
	setmetatable(v,vec2_meta)
	
	return v
end

local a = Vec2(40,29)
local b = Vec2(10,4)
local c = Vec2(0,0)
local d = Vec2(0,0)

c = a + b
d = a - b

print(c.x, c.y) --> prints 50,33
print(d.X, d.Y) --> prints nil,nil

Could you tell me why this doesn't work and how to fix it?

1 answer

✓ Accepted answer

It isn't working because you used uppercase x and y. Remember that Lua(u) is case-sensitive, so there is a difference between and, AND, And, etc.

Other than that everything else is fine.

1 comment

0

My bad, I'm used to capitals because of vectors and other things

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