Attempt to perform arithmetic (add) on nil and number Help

Hey im just trying to add 3 simple numbers and its gives me this error (in the title)

Pets.MultiplierValue = {
	
	["Bear"] = 1.15;
	["Fox"] = 1.17;
	
	
}
	

Pets.Multiplier = function(petName1, petName2, petName3)
	
	for i, v in pairs (Pets.MultiplierValue) do
		local ValPet1, ValPet2, ValPet3	
		
		if i == petName1 then
			ValPet1 = v
		end
		
		if i == petName2 then
			ValPet2 = v
		end
		
		if i == petName3 then
			ValPet3 = v
		end
		
		local returnedValue = ValPet1 + ValPet2 + ValPet3
		
		return returnedValue
	end
end

Any ideas why? (the returnedValue line gives that error)

That is probably because one of the petName variables are nil, to counter that you can try doing:

local returnedValue = (ValPet1 or 0) + (ValPet2 or 0) + (ValPet3 or 0)

Basically what that does it it makes it add 0 when the variable is missing(or nil in this case). There are better ways to go about this but this is the most immediate solution.

1 Like

to test it out i added

petMultiplier = petMultiplierModule.Multiplier("Bear", "Fox", "Bear")

And it still gives me that error any ideas?

You can try using []:

return MultiplierValue[petName1] + MultiplierValue[petName2] + MultiplierValue[petName3] 

What this code does is it fetches the string that you sent over the function and indexes the dictionarry with the corresponding string.
I found out why it doesn’t work, it’s because dictionaries don’t work with pairs.

2 Likes

You probably intended to put these lines outside of the loop? In the current constellation the loop will only run once (if at all).

Pets.Multiplier = function(petName1, petName2, petName3)
	local ValPet1, ValPet2, ValPet3

	for i, v in pairs (Pets.MultiplierValue) do	
		
		if i == petName1 then
			ValPet1 = v
		end
		
		if i == petName2 then
			ValPet2 = v
		end
		
		if i == petName3 then
			ValPet3 = v
		end
    end
		
	local returnedValue = ValPet1 + ValPet2 + ValPet3
		
	return returnedValue
end

Since you’re working with numbers, set the default value of all variables to zero, or else it will always error when someone doesn’t have three pets.

local ValPet1, ValPet2, ValPet3 = 0, 0, 0
1 Like

@VegetationBush Thank you really much this worked! @emojipasta thank you for the help aswell!

remove the “returnedValue” and it works