Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

DataStore not saving? (Filtering Enabled)

local DataStore = game:GetService("DataStoreService")
local ds = DataStore:GetDataStore("hellomynameijks45346345")

game.Players.PlayerAdded:connect(function(plr)
	
a = Instance.new("Folder", plr)
a.Name = "leaderstats"
	Vals = ds:GetAsync(plr.UserId)
	print(Vals)
	if Vals then
		for i, v in pairs(game.ReplicatedStorage.Values:GetChildren()) do
			print(v)
			Found = game.ReplicatedStorage.Values:FindFirstChild(v.Name)
			print("yes")
			if Found then
				print("Found")
			end
		end
	end
end)

game.Players.PlayerRemoving:connect(function(plr)
	Vals = {}
	for i, v in pairs(plr.leaderstats:GetChildren()) do
		print(v.Name)
		if v then
			
			table.insert(Vals, v.Name)
		end
	end
	ds:SetAsync(plr.UserId,Vals)
end)

I can't find the problem, when I leave the game, it prints the variable that was in my leaderstats. But when I then enter the game, the GetAsync return nil to Vals. Anyone know why?

1 answer

✓ Accepted answer

Perhaps the script doesn't have enough time to save the values, because the game shuts down before it manages to?

Try keeping the server alive till the data is saved by using game:BindToClose().

local plrs = {}
local allSaved = false

local function GetCount(t)
	local i = 0
	for _,v in pairs(t) do
		i = i + 1
	end
	return i
end

game.Players.PlayerAdded:Connect(function(plr)
	plrs[plr.Name] = true
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local Vals = {} --should be a local variable
	for i, v in pairs(plr.leaderstats:GetChildren()) do
		table.insert(Vals, v.Name) --shouldn't v.Value be here???
	end
	ds:SetAsync(plr.UserId,Vals)
	plrs[plr.Name] = nil
	if GetCount(plrs) == 0 then
		allSaved = true
	end
end)

game:BindToClose(function()
	repeat wait() until allSaved
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.