Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Datastore Script Calls Nil Value?

Asked by 9 years ago

I have this code:

local datastore = game:GetService("DataStoreService"):GetDataStore("Statistics")

game.Players.PlayerAdded:connect(function(player)
    local async = datastore:GetAsync(tostring(player.userId))
    local cash,xp = Instance.new("IntValue",player),Instance.new("IntValue",player)
    cash.Name = "Cash"
    xp.Name = "XP"
    cash.Value = async[1] --breaks here
    xp.Value = async[2]
    print(cash.Value,xp.Value)
end)

It breaks at where i said and outputs something like: async, a nil value How and why does it do this?

1 answer

Log in to vote
1
Answered by 9 years ago

To fix this, just add conditions if async is nil, then make a new table. Make sure you save the table to the datastore too!

local datastore = game:GetService("DataStoreService"):GetDataStore("Statistics")

game.Players.PlayerAdded:connect(function(player)
    local async = datastore:GetAsync(tostring(player.userId))
    if async == nil then --see if it's nil here
        async = {0,0} --default values of cash and xp
        datastore:SetAsync(tostring(player.userId),async) --optional to save, you could try saving when a player leaves if need to prevent data store limitations from causing a problem
    end
    local cash,xp = Instance.new("IntValue",player),Instance.new("IntValue",player)
    cash.Name = "Cash"
    xp.Name = "XP"
    cash.Value = async[1] --shouldn't break anymore :P
    xp.Value = async[2]
    print(cash.Value,xp.Value)
end)
Ad

Answer this question