Basically, DataStorage (DS) is a newer way of storing information through servers, and is referred to as an upgraded version of Data Persistence (DP)
How to use:
Let's say that you have a value that you call "Points" in your Script (which will store data for a player). It would basically look like this:
Now, let's say that a player joins, and you want this player to get this value stored in the DataStorage. This is what you would need to start with:
1 | local DataStore = game:GetService( "DataStoreService" ):GetDataStore( "Points" ) |
In the line above here, you can see us defining DataStore, which is easily reached using GetService. In the end of this line, you see us using a command: "GetDataStore". This command retrieves a DataStore, which in this case would be Points. If you are saving more dataStores, make sure that they don't have the same names.
Now, we want a player to get a point from for example clicking a button:
01 | local DataStore = game:GetService( "DataStoreService" ):GetDataStore( "Points" ) |
02 | local Button = workspace.Button.ClickDetector |
04 | Button.MouseButton 1 Click:connect( function (Player) |
05 | local key = "user_" .. Player.userId |
06 | DataStore:UpdateAsync(key, function (EarlierValue) |
07 | local newValue = EarlierValue or 0 |
08 | newValue = newValue + 1 |
In the script above, you can see us SAVING a value. Yes, that's right, saving! How did we do that? Well, as you can see, we use a basic button-clicking function for checking when a button is clicked. We then, assign a key. This key is really important, as it makes sure that the value is saved for that ONE SPECIFIC PLAYER! The reason we're using the User ID is because of the name changing system of ROBLOX, which could lead to a loss of data if the player changed their name. We then use a function on the DataStore, known as: "UpdateAsync". This function updates the earlier value of the dataStore. We then define a new Value, which is either the earlier value, or a new value. We then add a point to the player, and at last, we return the value so that it can be saved. But wait, what if we want to use this data in a leaderboard?
We would then use a basic function known as GetAsync. This function will retrieve the old value, and is used inside of variables:
1 | game.Players.PlayerAdded:connect( function (player) |
2 | key = "user_" .. player.userId |
3 | local Data = DataStore:GetAsync(key) |
I hope this helped!