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

Is there a way to make this safe and efficient?

For the past week, I've been noticing I lost my progress with this script. Can I use pcall or something to fix it? Thanks.

function onPlayerEntered(player)
wait()-- Change to wait for player longer.
player:WaitForDataReady()
repeat wait() until player:FindFirstChild("leaderstats")
if player.DataReady then
if player:findFirstChild("leaderstats") then
local score = player.leaderstats:GetChildren()
for i = 1,#score do
local ScoreLoaded = player:LoadNumber(score[i].Name)
wait()
if ScoreLoaded ~= 0 then
score[i].Value = ScoreLoaded
end
end
end
end
end

function onPlayerLeaving(player)
if player:findFirstChild("leaderstats") then
local score = player.leaderstats:GetChildren()
for i = 1,#score do
player:SaveNumber(score[i].Name,score[i].Value)
end
end
end

game.Players.PlayerAdded:connect(onPlayerEntered)
game.Players.PlayerRemoving:connect(onPlayerLeaving)

3 comments

1

Umm, Use DataStores, These old data saving things are Deprecated

0

DataStores are throttled and these are not. It is good to use both, but data persistence is unreliable.

0

And how do I do this?

1 answer

Hopefully this will help:

local Players = game:GetService("Players")
Players.PlayerAdded:connect(function(player)
	wait()-- Change to wait for player longer.
	player:WaitForDataReady()
	repeat wait() until pcall(function() return player["leaderstats"] end)
	if player.DataReady then
		if pcall(function() return player["leaderstats"] end) then
			local score = player.leaderstats:GetChildren()
			for _,v in pairs(score) do
				local c_s = score[v.Name]
				local ScoreLoaded = player:LoadNumber(c_s.Name)
				wait()
				if ScoreLoaded ~= 0 then
					c_s.Value = ScoreLoaded
				end
			end
		end
	end	
end)
Players.PlayerRemoving:connect(function(player)
	if pcall(function() return player["leaderstats"] end) then
		local score = player.leaderstats:GetChildren()
		for _,v in pairs(score) do
			local c_s = score[v.Name]
			player:SaveNumber(c_s.Name,c_s.Value)
		end
	end
end)

Only 28 lines. One less than the original. This is also way more reliable, efficient, and it should work.

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