My code is giving a weird error and I don't know how to fix it (Data stores)

Hey so I’m a bit new to using data stores and for some reason its not working, can someone help me?

this error pops up:

this is the code:

local Players = game:GetService(“Players”)
local DataStoreService = game:GetService(“DataStoreService”)
local Saver = DataStoreService:GetDataStore(“SaveLeaderstats”)

Players.PlayerAdded:Connect(function(player)
local Data = nil
local success, errormessage = pcall(function()
Data = Saver:GetAsync(tostring(player.UserId))
end)

if success then
if Data then
for i, v in pairs(Data) do
player:WaitForChild(“SpellsOwned”):GetChildren().Value = v
end
end
else
error(errormessage)
end
end)

local function Save(player)
local SavedData = {}
for _, v in pairs(player.SpellsOwned:GetChildren()) do
SavedData[v.Name] = v.Value
end

local success, errormessage = pcall(function()
Saver:SetAsync(tostring(player.UserId), SavedData)
end)
if not success then
error(errormessage)
end
end

Players.PlayerRemoving:Connect(Save)

game:BindToClose(function()
for _, v in pairs(Players:GetPlayers()) do
Save(v)
end
end)

2 Likes

Try adding a delay using a wait() function when looping through each of the spells as this will prevent too many requests being sent and add a delay when the game is closing as it may shut down before all of the data is saves.

Here is an example:

game:BindToClose(function()
wait(5)
end)

Try not to set the number too high as there is a limit where the server will shut down without continuing to wait; however I am unsure what it is.

Additionally, you could try reducing the amount of SetAsync() functions by storing the data in a table as a json string using http service. You may find this link useful:
HttpService:JSONEncode() Documention

You will also have to use :JSONDecode() when getting the data using :GetAsync() to convert it back into a table.

2 Likes

thank you, ill look over this later thanks for your help!

1 Like

I don’t know why it is giving that error, but I did find a mistake in your code

This is not setting the value for the individual spells, it’s instead trying to set a value in the table that contains all the children.

Basically, it’s trying to set a value for a table, not the actual spells.

Instead, you can replace it with something like this:

player:WaitForChild(“SpellsOwned”)[i].Value = v

That will go into the SpellsOwned folder, and set the spells value to whatever data they have on it.

If you want extra protection against errors, you can check if the spell exists before trying to do anything, like so:

if player:WaitForChild("SpellsOwned"):FindFirstChild(i) then
    player:WaitForChild("SpellsOwned")[i].Value = v
end
2 Likes

thank you so much for the help, i really appreciate it