Returns no errors.
DataStore = game:GetService("DataStoreService"):GetDataStore("BSI") Players = game:GetService("Players") game.Players.PlayerAdded:connect(function(player) local stats = Instance.new("IntValue", player) stats.Name = "stats" local Level = Instance.new("IntValue", stats) Level.Name = "Level" Level.Value = 1 local leader = Instance.new("IntValue", player) leader.Name = "leaderstats" local Kills = Instance.new("IntValue", leader) Kills.Name = "Kills" local key = "user "..player.userId local Saved = DataStore:GetAsync(key, function(Saved) print (Saved) --doesn't print Kills.Value = Saved or 0 DataStore:SetAsync(key, Saved) print (key, Saved) --does not print end) end) game.Players.PlayerRemoving:connect(function(player) local key = "user "..player.userId print (key.." left") --prints correctly local Saved = player.leaderstats.Kills.Value print (Saved.." value") --prints correctly DataStore:UpdateAsync(key, function(Saved) print (key, Saved) --print incorrectly, the key is always right, but saved is always 0 end) end)
When GetAsync
fails to retrieve anything, that means that it is a new key that hasn't been saved to yet. This can cause a lot of issues because GetAsync
doesn't return anything as expected. You should catch this case by doing something like the below...
-- assuming ds refers to the datastore local value = ds:GetAsync(key) or nil --> if it fails, nil. otherwise, the value.
In your UpdateAsync
, the reason why it is always printing 0 is because you are referring to the value that it currently is... aka the value that it was when the player joined the game. Notice that your Saved parameter on line 29 is named the same as your Saved value on line 27, which is probably the cause of some confusion. You should rewrite line 29 to 31 to the following...
DataStore:UpdateAsync(key, function(lastValue) print(key, Saved) return Saved -- this will save Saved to key in DataStore end)