Roblox: 'attempt to perform arithmetic on nil' – Fix
The error
ServerScriptService.Coins:14: attempt to perform arithmetic (add) on nil and number
What it means
One side of a +, -, * or / is nil. Typical causes:
- Reading an attribute that was never set:
part:GetAttribute("Coins")returnsnil. - A DataStore
GetAsyncreturnednilfor a new player. - A table key is misspelt, so
data.coinsis nil whiledata.Coinsexists.
If you forget .Value on an IntValue the error mentions an Instance instead of nil, which is a different fix.
The fix
-- default to 0 when nothing is stored yet
local coins = player:GetAttribute("Coins") or 0
player:SetAttribute("Coins", coins + 10)
-- DataStore: new players have no saved data
local ok, saved = pcall(function()
return store:GetAsync("player_" .. player.UserId)
end)
local data = (ok and saved) or { Coins = 0 }
data.Coins = (data.Coins or 0) + 10Use or 0 defaults wherever a value might not exist yet, and wrap DataStore calls in pcall.
Related errors
- roblox infinite yield possible
- roblox attempt to index nil with
- roblox remoteevent fireserver player argument
- roblox datastore request added to queue
Related tools: Roblox script generator · Roblox Lua error fixer · all script generators