Attempt to perform arithmetic (add) on nil and number

been trying to solve this one, I’m tryna make a donation Board and im using DataStore for this one.

Having a problem whenever server tries to perform this one:

--// Module
function DonateHandler.updatePlayerDonoAmount(player, amount)
	
	local userId = player.UserId
	local success, currentAmount = pcall(function()
		return donationStore:GetAsync(userId)
	end)
	
	currentAmount = currentAmount + amount
	
	donationStore:SetAsync(userId, currentAmount)
	
	cleanUpLeaderBoard()
	
end

and this is the server one

local function onProductPromptPurchased(playerId, id, isPurchased)
	
	local productInfo = MarketplaceService:GetProductInfo(id, Enum.InfoType.Product)
	local price = productInfo.PriceInRobux
	local player = game.Players:GetPlayerByUserId(playerId)
	
	DonationHandler.updatePlayerDonoAmount(player, price)
	
end

You’re probably finding that the datastore returns nil - as it has nothing there.

perhaps add a default value like:

CurrentAmount = CurrentAmount or 0

This should fix it.

1 Like

first thing I mainly notice is this line. when I normally do my DataStores, I usually create a variable called data and store the GetAsync value inside of it, rather than using a return statement, so I’d try something like that.

this error is fairly common and it means that you’re trying to add nil + a number.

on your first script, the GetAsync call is done inside a pcall. however, GetAsync occasionally fails, it doesn’t return anything, and instead just errors.

what you can do to prevent this is checking:

if not success then return end -- stop executing code if the pcall failed

OR, you can do this to make sure the number always exists

local currentAmount
repeat
     local success, result = (YOUR PCALL GOES HERE)
     if success then -- pcall was successful and a number was found
          currentAmount = result
          break -- stop the loop
     end
     task.wait(1) -- to avoid reaching limits in case this fails
until success

yup I noticed it as well earlier, thanks to everyone’s help

I simply just added a if and else statement whenever currentAmount is nil

1 Like