How to add a number into a dictionary value

function module.EXP(player)
	local plrFolder = game.ServerStorage.PlayerData:FindFirstChild(player.Name)
	if not plrFolder then return end
	local XP = game.HttpService:JSONDecode(plrFolder.Exp.Value)
	local weaponType = game.ServerStorage.Tools.Weapons.WeaponData[plrFolder.Weapon.Value].WeaponType.Value
	
	XP[weaponType] = XP[weaponType] + 10
end

on the second to last line I get ‘attempt to index number with ‘Fists’’
I’m trying to just add 10 points of the value to the dictionary though and I dunno how to do it otherwise

Since there’s not a value that has been indexed with weaponType yet, you’re pretty much adding a number to a nil value (nil + 10) which is actually not possible.

An easy solution to this would be checking if the value exists, if it doesn’t then create one:

local Value = XP[weaponType] -- gets the value of itself
if not Value then -- if it doesn't exist then
    XP[weaponType] = 0 -- set the value to a number
end
XP[weaponType] += 10 -- x += y is the same as x = x + y, but I recommend += since it makes your code look much better.
-- ^^ if a value already exists then the "if" statement will simply be ignored

Please let me know if you’re still receiving errors in the same function. Thank you!

1 Like

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