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

More issues with basic Data Store?

Asked by 9 years ago

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)
0
I think it's because you're replacing Saved when specifying the argument in your function, which will make it equal 0. Try changing the argument to a different name like Savedata. Spongocardo 1991 — 9y

1 answer

Log in to vote
1
Answered by
Unclear 1776 Moderation Voter
9 years ago

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)
0
Might the reason this isnt working be because its in a internal game of my main game, and I use the CreatePlace API to make this one BSIncorporated 640 — 9y
0
Also instead of saying "or nil" wouldnt "or 0" be the same thing, just giving an actual value? BSIncorporated 640 — 9y
Ad

Answer this question