Error in Data Saving!

Hello Developers!

Hi and I am Kamikaze and I am new to scripting. I need help with saving data. When I try my script, the data does not save! Here is the script:

                '''

local DataStoreService = game:GetService("DataStoreService")

local DataStore = DataStoreService:GetDataStore("DataStore")

game.Players.PlayerAdded:Connect(function(player)

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

local wins = Instance.new("IntValue")
wins.Name = "Wins"
wins.Parent = leaderstats

local data
local sucess, errormessage = pcall(function()
    data = DataStore:GetAsync(player.UserId..-wins)
end)

if sucess then
    wins.Value = data
else
    print("Error in getting your data")
    warn(errormessage)
 end
end)

game.Players.PlayerRemoving:Connect(function(player)

local sucess, errormessage = pcall(function()
    DataStore:SetAsync(player.UserId.."-wins",player.leaderstats.Wins.Value)
end)

if sucess then
    print("Hooray! Data Saved!")
else
    print("Oof! Your data was not saved!")
    warn(errormessage)
  end
end)
                      '''

Note that this script is in serverscriptservice
Also then error getting your data prints, but also the Hooray! Data saved! is also printed when you leave

1 Like

Where’s the code you need to fix?

If you need to learn about DataStores, learn from Data Stores | Documentation - Roblox Creator Hub
or watch tutorials, there are several available.

You could even use this data wrapper which has an extremely easy to use API:
How to use DataStore2 - Data Store caching and data loss prevention

1 Like

I do not have code to show, I just want to learn about saving data

1 Like

Try this: https://www.youtube.com/watch?v=DkYupSBUpes

2 Likes

This script is in serverscriptservice

On this line, I can spot an error. This part of the script is called the DataStore Key, and it’s what saves each player’s data uniquely. Each player has their own key. Your error comes in the part that says -wins. Since this part is not wrapped in speech marks, it does not match the key that appears later on when you are actually saving the player’s data.

The way to fix this is by wrapping the -wins part in speech marks so it matches the key that you are trying to save to further down in the script. I have showed how to do this below.

local data
local sucess, errormessage = pcall(function()
    data = DataStore:GetAsync(player.UserId.."-wins")
end)

Hopefully this was helpful.

1 Like