How do you save a player's leaderstat? I tried this, but the output said, "HTTP 0 (CURL error (curl_easy_perform): Failure when receiving data from the peer (56))" Also, should I use SetAsync or UpdateAsync to save a player's level every 64 seconds? Thanks!
local DataStore = game:GetService("DataStoreService"):GetDataStore("Level") while true do for _, player in pairs(game.Players:GetPlayers()) do local key = "user_" .. player.userId DataStore:SetAsync(key, player.leaderstats.Level.Value) end wait(64) end
Hi GatitosMansion!
As cabbler has suggested, you really don't need to update a player's DataStore until he leaves (under most circumstances.)
A better way to go about doing things might well be the following:
local DataStore = game:GetService("DataStoreService"):GetDataStore("Level"); -- Set this to whatever the default level value should be. local DefaultValue = nil; game.Players.PlayerRemoving:connect(function(player) local key = "user_" .. player.UserId; local levelValue = player:FindFirstChild("Level", true); DataStore:SetAsync( key, (levelValue and levelValue.Value or DefaultValue) ); end);
This only runs when the player leaves (which is ultimately all that is required,) and has a fallback for when the value object Level
does not exist. Efficient and reliable.
UpdateAsync is particularly useful when you want to get the current value and perform certain operations on a value before saving it. Suppose we want a slightly easier version of the current level loaded when a player rejoins. Consider the following:
game.Players.PlayerRemoving:connect(function(player) local key = "user_" .. player.UserId; local levelValue = player:FindFirstChild("Level", true); DataStore:UpdateAsync(key, function(currentValue) local newValue = currentValue or DefaultValue; newValue = newValue .. "_Rejoined"; return newValue; end); end);
When the player rejoins, we now know to load a version of the level that is slightly easier so that the player has time to, eh, 'get in the groove' of the game. A fairly specialized example, maybe, but an example where UpdateAsync may be useful. In your case, SetAsync would be just fine, since we're not worried about the current value, only the new value.
I hope this helps! Have a good one, GatitosMansion, and best of luck with your game!
Best regards, tkcmdr
Edit: Elaborated a bit on the use of UpdateAsync. Improved the clarity of the explanations.
I believe "curl_easy_perform" is an overload error. Datastores don't like when you do a lot of updates at one time. As a general rule for datastores, you getAsync when the player joins, setAsync when the player leaves, and store their data in a local table if you need to manipulate it during the game.
You only need to use updateAsync if the previous data matters and the data is subject to being changed unexpectedly. I doubt either of those are true for you.