Can you guys write simple code using datastores?

I’m having a really hard time understanding datastores. I just need an example to go off of.

local ds = game:GetService("DataStoreService"):GetDataStore("Datastore") --the datastore

game.Players.PlayerAdded:Connect(function(plr) --player joins
    local value = Instance.new("NumberValue")
    value.Name = "TestValue"
    value.Parent = plr
    
    local data = ds:GetAsync(plr.UserId)
    
    value.Value = data or 0 --set it to the saved data or 0
    
    while task.wait(1) do
        value.Value += 1 --add to the value so you can see
    end
end)

game.Players.PlayerRemoving:Connect(function(plr) --when player leaves
    ds:SetAsync(plr.UserId, plr.TestValue.Value) --save value
end)

game:BindToClose(function() --for when the game closes and PlayerRemoving doesn't fire
    for i, plr in pairs(game.Players:GetPlayers()) do --go through all of the players
        ds:SetAsync(plr.UserId, plr.TestValue.Value) --save the value
    end
end)

this should be a good example. Also, you can wrap the saving and getting of the data in pcalls, which most people use (I don’t though)

local ds = game:GetService("DataStoreService"):GetDataStore("Datastore") --the datastore

game.Players.PlayerAdded:Connect(function(plr) --player joins
    local value = Instance.new("NumberValue")
    value.Name = "TestValue"
    value.Parent = plr
    value.Value = 0
    
    local data

    local success, error = pcall(function()
        data = ds:GetAsync(plr.UserId, plr.TestValue.Value) --get the data
    end)
    
    if success then
        value.Value = data
    end
    
    while task.wait(1) do
        value.Value += 1 --add to the value so you can see
    end
end)

game.Players.PlayerRemoving:Connect(function(plr) --when player leaves
    local success, error = pcall(function()
        ds:SetAsync(plr.UserId, plr.TestValue.Value) --save the value
    end)
        
    if not success and error then
        warn(error)
    end
end)

game:BindToClose(function() --for when the game closes and PlayerRemoving doesn't fire
    for i, plr in pairs(game.Players:GetPlayers()) do --go through all of the players
        local success, error = pcall(function()
            ds:SetAsync(plr.UserId, plr.TestValue.Value) --save the value
        end)
        
        if not success and error then
            warn(error)
        end
    end
end)

if your talking about saving player data then have you tried looking here
https://create.roblox.com/docs/tutorials/scripting/intermediate-scripting/saving-data

i know its not exactly what you where looking for but i think this could help you understand it a little bit in depth

Before you read this, please go to the official page for DataStores. If you still do not understand, read further.

IMPORTANT NOTES:

  1. DataStores cannot be handled using a LocalScript. Attempting to do so will cause an error.
  2. Go to Studio Settings, Security and turn on Enable Studio Access to API Services.

Not an expert, but here you go.

CREATING AND GETTING DATASTORE VALUES

local dataStoreService = game:GetService("DataStoreService") --retrieves DSS so we can use it in our game.
local newDataStore = dataStoreService:GetDataStore("placeholderName")

Basically, :GetDataStore() creates a new datastore under DataStoreService. The words inside the brackets are the name of the dataStore.

local success, errorMessage = pcall(function()
		newDataStore:GetAsync("Code")
end)
if success then
		print("Yay! DataStore loaded properly")
	elseif errorMessage then
		warn("Problem with loading datastore. Error message is as follows:"..errorMessage)
end

:GetAsync() reads the data from the specific datastore inside the brackets. If you have not made any changes to it, the value should be nil.
pcall(function() basically wraps your code inside this sort of safeguard, which tells you if they retrieved the value of the datastore properly. success obviously means it returned properly, and errorMessage is the errorMessage that pops up if it doesn’t work.

You can also remove a DataStore using :RemoveAsync()

SETTING DATASTORE VALUES
There are three types of ways you can change values of datastores in your game, which are as follows:

  1. SetAsync
  2. UpdateAsync
  3. IncrementAsync

SETASYNC
SetAsync is a direct and quick way to change datastores. However, it is risky to use it many times in a row, as it may flood the server with data requests and may not change the values at ALL.
Code example:

local success, errorMessage = pcall(function() --once again, we wrap it in pcall to catch errors
		return newDataStore:SetAsync("Code", 2453)
	end)
	if success then
		print("Changed code!")
	elseif errorMessage then
		warn(errorMessage)
end

UPDATEASYNC
Quoted from the official page for DataStores:

GlobalDataStore:SetAsync() is best for a quick update of a specific key, and it only counts against the write limit. However, it may cause data inconsistency if two servers attempt to set the same key at the same time.

GlobalDataStore:UpdateAsync() is safer for handling multi-server attempts because it reads the current key value from the server that last updated it before making any changes. However, it’s somewhat slower because it reads before it writes, and it also counts against both the read and write limit.

Code example:

local success, errorMessage = pcall(function() --once again, we wrap it in pcall to catch errors
		newDataStore:UpdateAsync("Code", function()
             return 8572 --the data we want to set the DataStore as
        end
	end)
	if success then
		print("Changed code!")
	elseif errorMessage then
		warn(errorMessage)
end

INCREMENT ASYNC
IncrementAsync is used for increasing the value of a number. Do not ever use it with anything other than a number or it will cause an error.
Code example:

local success, errorMessage = pcall(function() --once again, we wrap it in pcall to catch errors
		return newDataStore:IncrementAsync("Code", 4) --we increased the number by 4
	end)
	if success then
		print("Changed code!")
	elseif errorMessage then
		warn(errorMessage)
end

I’ve probably made some errors

You should try use DataStore2 as it’s very simple and you can make a complete DataStore with very short code

Here is an example:

local Ds2 = require(game.ServerStorage:WaitForChild('DataStore2')

Ds2.Combine('Items','Coins') -- You can add more after Coins and change the name of Item or Coins

game.PlayersAdded:Connect(function(player))

          local CoinsDs = Ds2('Coins',player)

         local leaderstats = Instance.new('Folder')
         leaderstasts.Name = 'leaderstats'
         leaderstats.Parent = player

        local Coins = Instance.new('NumberValue')
        Coins.Name = 'Coins'
        Coins.Parent = leaderstats
        Coins.Value = CoinsDs:Get(0) -- gets the value of the players coin and if there isn't any it set it to 0

       CoinsDs:OnUpdate(function(newv)) -- whenever the DataStore is updated this is triggered

       Coins.Value = newv

     end)

end)

while wait(5) do

       for i,v in pairs(game.Players:GetPlayers()) do -- every 5 seconds loops through all players 

              local PCoinDs = Ds2('Coins',v) -- gets players Coins DataStore

             PCoinDs:Increment(10) -- Adds to it by 10

      end
end

This is an example of a simple Coins DataStore which you could use in a simulator or tycoon

I know, I was just doing the retro method, y’know? Anyways, seems like a cool module!