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

How can I fix this Data Persistence loop?

I'm trying to use a loop to save multiple number values to a player when they join the game. The keys table contains multiple tables. Each sub table has two values: the data persistence key and the instance name. Basically, when a player joins the game, I want the keys table to be looped through. If a number value is found with the name of v[2], then it's value should be loaded as v[1] (the key). Every five seconds, I want all players to be looped through, and have their data be saved. I'm not sure if I'm even close to being right with this, but I figured I'd give it a shot. The output isn't saying anything is wrong, by the way.

local keys = {
	{"cpc", "CPC"},
	{"cookies", "Cookies"},
	{"cps", "CPS"}
}

game.Players.PlayerAdded:connect(function(player)
	player:WaitForDataReady()
	local location = player.PlayerGui.CookieClicker.Data
	for i, v in pairs(keys) do
		pcall(function()
			if location:FindFirstChild(v[2]) then
				location[v[2]].Value = player:LoadNumber(v[1]) or 0
			end
		end)
	end
end)

while wait(5) do
	for _, player in pairs(game.Players:GetPlayers()) do
		local location = player.PlayerGui.CookieClicker.Data
		for i, v in pairs(keys) do
			pcall(function()
				if location:FindFirstChild(v[2]) then
					player:SaveNumber(v[1], location[v[2]].Value)
				end
			end)
		end
	end
end

2 comments

0

Typo: I'm trying to use a loop to load* multiple number values to a player when they join the game.

0

May I reformat this in DataStore?

1 answer

I would say you are doing it mostly right, a few problems, but for the most part you are doing things right.

One thing, though, is you should really be saving when the player leaves. Not every 5 seconds. This can easily be achieved with the PlayerRemoving method.

game.Players.PlayerRemoving:connect(function(Player)
	-- Save their data.
end)

When saving a leaving player's data, you'll want to make sure their data is ready to be saved to. This can be done with the WaitForDataReady method, but in this instance I prefer the DataReady property. Personal preference, though, as both work.

if Player.DataReady then
	-- Now we actually save the data!
end

And finally, for saving, you are doing things right from what I saw.

1 comment

0

He looked over the post and never answered even though he had a dire situation, I answered but no response ...

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