Stellar AI

Errors

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") returns nil.
  • A DataStore GetAsync returned nil for a new player.
  • A table key is misspelt, so data.coins is nil while data.Coins exists.

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) + 10

Use or 0 defaults wherever a value might not exist yet, and wrap DataStore calls in pcall.

Related errors

Related tools: Roblox script generator · Roblox Lua error fixer · all script generators