Setting Up and Loading Data
First you’ll want to setup a template of the data you need to save, for example:
function GetDataTemplate()
return{
Exp = 0;
Level = 0;
Cash = 0;
Items = {};
}
end
When a player enters the game, you can use GetAsync(key) to check for existing data. I would strongly recommended using the player’s UserId for the key, as there is no chance of this being altered (unlike the player’s username). Make sure to wrap your requests in pcalls because they can sometimes fail:
local success, pdata = pcall(function() return dataStore:GetAsync(key) end)
Once you’ve done this, you’ll want to make three checks:
-
Were you able to access the dataStore? (i.e. does success == true?) If not, then set the player’s data to false and take the appropriate action (e.g. warn the user or teleport them back into the game)
- If successful, does the player’s data exist? If not, they’re a new player, and you need to setup their data (i.e. using GetDataTemplate())
- Else the player has existing data; use this. You may want to compare this data against GetDataTemplate() if you plan on adding more data to your template after your game has been released.
Saving Data
There are various stages where you might want to save a player’s data. For example:
- When the player leaves the game
- Every x seconds
- When the player purchases an important item
There are four methods of writing data:
- UpdateAsync
- SetAsync
- IncrementAsync
- RemoveAsync
In your situation, I would strongly recommend using UpdateAsync() as this enables you to compare the player’s current data with the data about to be overwritten, making any adjustments as needed. For example, you could define a variable called ‘DataID’ and increase this value by 1 every time the player’s data is saved. If both IDs do not much (e.g. because the player’s data failed to load correctly), then you can cancel the save and prevent the player’s data being overwritten.
You must also consider limitations when using functions like UpdateAsync(). For example, you must leave a 6 second interval before updating the same key again. You can find out more on Datastore limitations and errors here: Documentation - Roblox Creator Hub
There are range of useful resources for creating datastores. For example:
https://developer.roblox.com/articles/Data-store
https://devforum.roblox.com/t/good-practices-for-datastorage/81985/5