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

BEST way to save data?

Asked by
LuaQuest 450 Moderation Voter
8 years ago

Just wondering, what would be the best method to save data with DataStoreService? I know how to use both SetAsync and UpdateAsync, but when should I use them? What would be better, a spawned loop that auto-saves data every few seconds or a PlayerRemoving event that saves it when the player leaves?

Here's my code for both cases:

Auto-save method:

local Datastore = game:GetService("DataStoreService"):GetDataStore("Example")
local Inc = Datastore:GetAsync("Test") or 0

spawn(function()
    while wait(5) do
        print("Autosaving...")
        Datastore:UpdateAsync("Test",function()
            return New
        end)
        print("Saved")
    end
end)

PlayerRemoving method:

local Players = game:GetService("Players")
local Datastore = game:GetService("DataStoreService"):GetDataStore("Example")
local Data = {}

Players.PlayerAdded:connect(function(Player)
    Data[Player.UserId] = Datastore:GetAsync("Test") or 0
    while wait(1) do
        Data[Player.UserId] = Data[Player.UserId] + 1
    end
end)

Player.PlayerRemoving:connect(function(Player)
    Datastore:UpdateAsync(Player.UserId,function()
        return Data[Player.UserId]
    end)
end)

Confusion

I feel like the PlayerRemoving one is a lot better, and more efficient, but there are also times when it won't save. Whereas the auto-save method seems to work fine, but over a period of time takes longer to save data and doesn't seem to efficient. Any help?

1 answer

Log in to vote
1
Answered by 8 years ago

Auto saving is almost always better in any situation, because unexpected situations can occur. But, every 5 seconds is a bit much.

In a game I made, I used both: I autosaved every 60 seconds, and also when the player left. Make sure that you use OnClose to make sure that the data actually saves before the last player leaves the game.

Ad

Answer this question