.__add isnt working

learning metatables from a youtube tutorial. im not sure why it prints 20 for the first and 4th for the next. my intention is for it to print 24 for the 2nd print. ive copied exactly for the second time, but i still cannot achieve the desired output

local mytable = {}
mytable.value = 20

local metatable = {}
metatable.__add = function(t,v)
	t.value = v
	return t
end

setmetatable(mytable, metatable)

print(mytable)

mytable += 4

print(mytable)

[“value”] = 20
[“value”] = 4

t.value = v

I don’t deal with metatables, but it seems it is doing exactly what you coded it to do - it is setting the value of mytable to the value that you ‘added’ to it, being 4. If you make make t.value = v be t.value += v, does it give the desired output?

in the tutorial, the code runs as
[“value”] = 20
[“value”] = 24

ive copied exactly as well so im not sure what is the problem with it now

Can you please link the video? I’ll ensure that you did type it all the same

https://www.youtube.com/watch?v=bk8UVm-gxBs&t=527s 7:18

From the video:
image

They are doing +=, while you are doing =.

1 Like

thank you. my bad, i didnt catch that because i was referring from my phone.

1 Like

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