Help on metatables/metamethod

What would you like to achieve?

Learn about Metatables.


What are your problems for today…?

Cannot add 2 numbers.

Code

local function mathProblem(num, num2)
		num = num + num2
    return num + num2
end
 
local metatable = {

  __index = function(obj, numb, numb2)
	local answer = mathProblem(numb, numb2)
	obj[numb] = obj[numb] + numb2
	return numb
end

}

local t = setmetatable({}, metatable)
 
print(t[1 + 2])

Output

Players.Player1.PlayerGui.Loading.LocalScript:2: attempt to perform arithmetic (add) on number and nil

This happens in metatables function

1 Like

numb2 is nil, because really when you do print(t[1 + 2]) that is the same thing as print(t[3]) , it’s not two different values being passed to your __index function, is there a reason you are using Metamethods for this in the first place though?


On another note you could use the __add metamethod to check what variable/metatable is being arithmetically added to another variableor number, but if you are wanting to check when two numbers are added or divided (etc.) together In general, just doing something like 1 + 2 likely won’t work because numbers aren’t variables and or metatables, you would have to make them into variables and probably define them somewhere within your meta table. ( if that makes sense)


Here is a random example of using __add to subtract a variable from a number:

local a = {1, __add = function(Table,val)
   return  val -  Table[1]
end}
setmetatable(a,a)
print(a + 4) ----->>>> 3

But then again doesn’t that defeat the purpose of using metamethods in the first place, when you could easily do 4- 1 or:

local a = 1
local b = 4
print(b - a) --->>>> 3

or even

print("4" - "1") --->>>> 3
6 Likes

at this time i would nearly consider myself advanced but just under it, i understand it now great job

:white_check_mark: :heart: :roblox:

1 Like