Need global leaderboard help, system doesn't update itself nor work

Hey everyone, I’ve been trying to solve this issue for quite a while and I give up and I need to ask for help because even roblox assistant doesn’t work anymore here.
So basically my issue is: at first it worked kinda because it showed every player but the values were outdated, then I changed it so it only shows from cash datastore and after some time it stopped working, now it doesn’t show any errors and doesn’t work.

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local dataStore = DataStoreService:GetOrderedDataStore("cashds_1")

local surfaceGui = script.Parent
local sample = script:WaitForChild("Sample")
local sf = surfaceGui:WaitForChild("ScrollingFrame")
local uiListLayout = sf:FindFirstChildOfClass("UIListLayout") or Instance.new("UIListLayout")
uiListLayout.SortOrder = Enum.SortOrder.LayoutOrder
uiListLayout.Parent = sf


local existingLabels = {}  -- Use a dictionary to keep track of existing labels

local function getPlayerCash(userId)
	print(userId)
	local key = tostring(userId)
	local success, cash = pcall(function()
		local data = dataStore:GetAsync(key)
		print(data)
		if data and data.Cash then
			return data.Cash
		else
			return 0
		end
	end)
	if success then
		return cash
	else
		warn("[Global Leaderboard] Error getting cash for player", userId)
		return 0
	end
end


local function getTopPlayers()
	local success, pages = pcall(function()
		return dataStore:GetSortedAsync(false, 100, 1, 10e30)
	end)

	if not success then
		warn("[Global Leaderboard] Error getting pages:", pages)
		return nil
	end

	return pages:GetCurrentPage()
end


local function updateLeaderboard()
	print("[Global Leaderboard] Updating leaderboard at", os.date("%Y-%m-%d %H:%M:%S"))

	local top = getTopPlayers()

	if not top then
		return
	end

	-- Clear existing labels
	for _, label in pairs(existingLabels) do
		label:Destroy()
	end

	existingLabels = {}  -- Reset the dictionary

	for rank, entry in ipairs(top) do
		local userId = entry.key

		print("[Global Leaderboard] Looking up player for userId:", userId)

		local player = Players:GetPlayerByUserId(userId)

		local color = Color3.new(1, 1, 1)

		if rank == 1 then
			color = Color3.new(1, 1, 0)
		elseif rank == 2 then
			color = Color3.new(0.9, 0.9, 0.9)
		elseif rank == 3 then
			color = Color3.new(166, 112, 0)
		end

		local new = sample:Clone()
		new.Name = userId
		new.LayoutOrder = rank
		new.Parent = sf

		local playerNameLabel = new:WaitForChild("playerName")
		local rankLabel = new:WaitForChild("rank")
		local valueLabel = new:WaitForChild("value")

		if player then
			playerNameLabel.Text = player.Name
		else
			local success, username = pcall(function()
				return Players:GetNameFromUserIdAsync(userId)
			end)

			if success then
				playerNameLabel.Text = username
			else
				warn("[Global Leaderboard] Unable to get username for userId", userId)
				playerNameLabel.Text = "Unknown"
			end
		end

		local cash = getPlayerCash(userId)
		entry.value = cash

		rankLabel.Text = "#" .. rank
		rankLabel.TextColor3 = color
		valueLabel.Text = cash
		valueLabel.TextColor3 = color
		playerNameLabel.TextColor3 = color

		print("[Global Leaderboard] Player:", player and player.Name or "Not in game", "Cash:", cash)
		print("[Global Leaderboard] UI updated for player", userId, "with cash value", cash, "at", os.date("%Y-%m-%d %H:%M:%S"))

		existingLabels[userId] = new  -- Add the new label to the dictionary
	end
end


local function onPlayerChanged(player)
	local success, result = pcall(function()
		updateLeaderboard()
	end)

	if not success then
		warn("[Global Leaderboard] Error updating leaderboard:", result)
	end

	local playerGui = player:FindFirstChildOfClass("PlayerGui")
	if playerGui then
		local coinLeaderboardGui = playerGui:FindFirstChild("coinLeaderboard")
		if coinLeaderboardGui then
			local surfaceGui = coinLeaderboardGui:FindFirstChild("SurfaceGui")
			if surfaceGui then
				local sf = surfaceGui:FindFirstChild("ScrollingFrame")
				if sf then
					local success, result = pcall(function()
						updateLeaderboard()
					end)

					if not success then
						warn("[Global Leaderboard] Error updating leaderboard:", result)
					end
				end
			end
		end
	end
end

Players.PlayerAdded:Connect(onPlayerChanged)
Players.PlayerRemoving:Connect(onPlayerChanged)

-- Function to automatically update leaderboard every 5 seconds
local function autoUpdateLeaderboard()
	while true do
		local success, result = pcall(function()
			updateLeaderboard()
		end)

		if not success then
			warn("[Global Leaderboard] Error updating leaderboard:", result)
		end
		wait(5) -- Update every 5 seconds
	end
end

-- Start the automatic update loop
autoUpdateLeaderboard()

Any help is welcomed because it hurts my head fixing it. I literally spent hours and days with little but no result.

Can anyone help? The issue isn’t much of a deal but I don’t have an idea what doesn’t work here to be honest. In past the output showed that the data cannot be retrieved. Now it just doesn’t work.

dude I’m not a pro scripter but I can give you my script it updates:

local DataStoreService = game:GetService(“DataStoreService”)
local WinsLeaderboard = DataStoreService:GetOrderedDataStore(“WinsLeaderboard”)

local function updateLeaderboard()
local succes, errorMessage = pcall(function()
local Data = WinsLeaderboard:GetSortedAsync(false, 5)
local WinsPage = Data:GetCurrentPage()
for Rank, data in ipairs (WinsPage) do
local userName = game.Players:GetNameFromUserIdAsync(tonumber(data.key))
local Name = userName
local Wins = data.value
local isOnLeaderboard = false
for i, v in pairs(game.Workspace.GlobalLeaderboard.LeaderboardGui.Holder:GetChildren()) do
if v.Player.Text == Name then
isOnLeaderboard = true
break
end
end

		if Wins and isOnLeaderboard == false then
			local newLbFrame = game.ReplicatedStorage:WaitForChild("LeaderBoardFrame"):Clone()
			newLbFrame.Player.Text = Name
			newLbFrame.Wins.Text = Wins
			newLbFrame.Rank.Text = "#"..Rank
			newLbFrame.Position = UDim2.new(0,0, newLbFrame.Position.Y.Scale + (.08 * #game.Workspace.GlobalLeaderboard.LeaderboardGui.Holder:GetChildren()), 0)
			newLbFrame.Parent = game.Workspace.GlobalLeaderboard.LeaderboardGui.Holder
		end
	end
end)

if not succes then
	print(errorMessage)
end

end

while true do
for _, Player in pairs(game.Players:GetPlayers()) do
WinsLeaderboard:SetAsync(Player.UserId, Player.leaderstats.Wins.Value)
end

for _, frame in pairs(game.Workspace.GlobalLeaderboard.LeaderboardGui.Holder:GetChildren()) do
	frame:Destroy()
end

updateLeaderboard()
print("Updated!")

wait(10)

end

Your script probably only works for your model, in my case I need a fix.

Can anybody else help please? I keep trying to fix the issue but it still doesn’t work. Maybe someone who understands the code better than me will see it?

Maby add a delay. While true loops are so error offensifly esspecially in combination of get methods. : ) This is a high language not assembler. If yk

while true do
for _, Player in pairs(game.Players:GetPlayers()) do
WinsLeaderboard:SetAsync(Player.UserId, Player.leaderstats.Wins.Value)
end

Roblox AI:According to the Roblox documentation, for each function that uses SetAsync() you can make a total of 60 + numPlayers × 10 requests per minute

Pls make a local var who`s been changing in the true loop and only set all the player data when they left or every fife minutes.

Uh that’s not my code, you referred to the code of the person who replied. My code is the code in the post!

1 Like

I need help with scripting! Numbers of players in leaderboard get donate buttons so is it possible?

local statsName = "Coins"
local maxItems = 100
local minValueDisplay = -9.223372e18
local maxValueDisplay = 9.223372e18
local abbreviateValue = false
local updateEvery = 60 
local headingColor = Color3.fromRGB(0, 0, 0)

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local DataStore = DataStoreService:GetOrderedDataStore("GlobalLeaderboard95" .. statsName)
local Frame = script.Parent.Frame
local Contents = Frame.Contents
local Template = script.objTemplate

local COLORS = {
	Default = Color3.fromRGB(255, 255, 255),
	Gold = Color3.fromRGB(255, 204, 51),
	Silver = Color3.fromRGB(204, 204, 204),
	Bronze = Color3.fromRGB(153, 102, 51)
}
local ABBREVIATIONS = { "K", "M", "B", "T" }

local function toHumanReadableNumber(num)
	if num < 1000 then
		return tostring(num)
	end
	
	local digits = math.floor(math.log10(num)) + 1
	local index = math.min(#ABBREVIATIONS, math.floor((digits - 1) / 3))
	local front = num / math.pow(10, index * 3)
	
	return string.format("%i%s+", front, ABBREVIATIONS[index])
end

local function getItems()
	local data = DataStore:GetSortedAsync(false, maxItems, minValueDisplay, maxValueDisplay)
	local topPage = data:GetCurrentPage()

	Contents.Items.Nothing.Visible = #topPage == 0 and true or false

	for position, v in ipairs(topPage) do
		local userId = v.key
		local value = v.value
		local username = "[Not Available]"
		local color = COLORS.Default

		local success, err = pcall(function()
			username = Players:GetNameFromUserIdAsync(userId)
		end)

		if position == 1 then
			color = COLORS.Gold
		elseif position == 2 then
			color = COLORS.Silver
		elseif position == 3 then
			color = COLORS.Bronze
		end

		local item = Template:Clone()
		item.Name = username
		item.LayoutOrder = position
		item.Values.Number.TextColor3 = color
		item.Values.Number.Text = position
		item.Values.Username.Text = username
		item.ProfilePicture.Image = "https://www.roblox.com/bust-thumbnail/image?userId=".. userId .."&width=420&height=420&format=png"
		item.Values.Value.Text = abbreviateValue and toHumanReadableNumber(value) or value
		item.Parent = Contents.Items
	end
end

script.Parent.Parent.Color = headingColor
Frame.Heading.ImageColor3 = headingColor

while true do
	for _, player in pairs(Players:GetPlayers()) do
		local statsValue = player:FindFirstChild(statsName)

		if not statsValue then
			warn("Couldn't find " .. statsName .. " in leaderstats!")
			break
		end

		pcall(function()
			DataStore:UpdateAsync(player.UserId, function()
				return tonumber(statsValue.Value)
			end)
		end)
	end

	for _, item in pairs(Contents.Items:GetChildren()) do
		if item:IsA("ScrollingFrame") then
			item:Destroy()
		end
	end

	getItems()

	wait()
	Frame.Heading.Heading.Text = statsName .. " Leaderboard"
	wait(updateEvery)
end

Well, I Need Help to Make Donate On Players!