DataStore
This item only works when running on the server. Server
Wraps the datastore object to provide async cached loading and saving. See DataStoreStage for more API.
Has the following features
- Automatic saving every 5 minutes
- Jitter (doesn't save all at the same time)
- De-duplication (only updates data it needs)
- Battle tested across multiple top games.
local playerMoneyValue = Instance.new("IntValue")
playerMoneyValue.Value = 0
local dataStore = DataStore.new(DataStoreService:GetDataStore("test"), test-store")
dataStore:Load("money", 0):Then(function(money)
playerMoneyValue.Value = money
dataStore:StoreOnValueChange("money", playerMoneyValue)
end):Catch(function()
-- TODO: Notify player
end)
To use a datastore for a player, it's recommended you use the PlayerDataStoreService. This looks something like this. See ServiceBag for more information on service initialization.
local serviceBag = ServiceBag.new()
local playerDataStoreService = serviceBag:GetService(require("PlayerDataStoreService"))
serviceBag:Init()
serviceBag:Start()
local topMaid = Maid.new()
local function handlePlayer(player)
local maid = Maid.new()
local playerMoneyValue = Instance.new("IntValue")
playerMoneyValue.Name = "Money"
playerMoneyValue.Value = 0
playerMoneyValue.Parent = player
maid:GivePromise(playerDataStoreService:PromiseDataStore(Players)):Then(function(dataStore)
maid:GivePromise(dataStore:Load("money", 0))
:Then(function(money)
playerMoneyValue.Value = money
maid:GiveTask(dataStore:StoreOnValueChange("money", playerMoneyValue))
end)
end)
topMaid[player] = maid
end
Players.PlayerAdded:Connect(handlePlayer)
Players.PlayerRemoving:Connect(function(player)
topMaid[player] = nil
end)
for _, player in pairs(Players:GetPlayers()) do
task.spawn(handlePlayer, player)
end
Properties
Saving
Prop that fires when saving. Promise will resolve once saving is complete.
Functions
new
Constructs a new DataStore. See DataStoreStage for more API.
SetCacheTime
DataStore:
SetCacheTime
(
cacheTimeSeconds:
number?
) →
(
)
Sets how long the datastore will cache for
GetFullPath
DataStore:
GetFullPath
(
) →
string
Returns the full path for the datastore
DidLoadFail
DataStore:
DidLoadFail
(
) →
boolean
Returns whether the datastore failed.
PromiseLoadSuccessful
Returns whether the datastore has loaded successfully.\
Save
Saves all stored data.
Load
DataStore:
Load
(
keyName:
string
,
defaultValue:
any?
) →
any?
Loads data. This returns the originally loaded data.