Tonumber() turn a value nil

Right, now I’m making a simple global player leaderboard while following this tutorial, to add I’m using ProfileService for handling “data saving”

https://www.youtube.com/watch?v=sXpuGnVzsxw&t=969s&ab_channel=TheDevKing

Now I’ve run into a problem when trying to use tonumber() on the value key it changes the value to a nil,
Below you can see the console output of these prints:

print(data)
print(data.key)
print(tonumber(data.key))

image

Heres my code:

local function updateLeaderboard()
		local Data = DeathsLeaderboard:GetSortedAsync(false, 5)
		local DeathsPage = Data:GetCurrentPage()
	for rank, data in pairs(DeathsPage) do
		if data then
			print(data)
			print(data.key)
			print(tonumber(data.key))
			local username = game.Players:GetNameFromUserIdAsync(tonumber(data.key))
			local Deaths = data.Value
			local isOnLeadearboard = false
			for i, v in workspace.Folder.LeaderBoards.DeathsLeaderboard.Main.SurfaceGui.Holder:GetChildren() do
				if v.Player.Text == username then
					isOnLeadearboard = true
					break
				end
			end
			if Deaths and not isOnLeadearboard then
				local newLbFrame = RepStorage.GUIS:WaitForChild("LeaderboardFrame"):Clone()
				newLbFrame.Player.Text = username
				newLbFrame.Deaths.Text = Deaths
				newLbFrame.Rand.Text = "#"..rank
				newLbFrame.Position = UDim2.new(0, 0, newLbFrame.Position.Y.Scale + (.08 + #workspace.Folder.LeaderBoards.DeathsLeaderboard.Main.SurfaceGui.Holder:GetChildren()), 0)
				newLbFrame.Parent = workspace.Folder.LeaderBoards.DeathsLeaderboard.Main.SurfaceGui.Holder
			end
		end
	end
end

while true do
	for _, plr in game.Players:GetPlayers() do
		DeathsLeaderboard:SetAsync(plr.UserId, plr.leaderstats.Deaths.Value)
	end
	
	for _,v in pairs(workspace.Folder.LeaderBoards.DeathsLeaderboard.Main.SurfaceGui.Holder:GetChildren()) do
		if v:IsA("Frame") then
			v:Destroy()
		end
	end
	
	updateLeaderboard()
	print("Dated")
	wait(5)
end

I hope that someone can help me out on this case that’s all…

1 Like

If you just want to get the number from the key, you can use string.match():

local key = data.key
local justNumber = string.match(key, "%d+")
print(tonumber(justNumber)) --> prints the number from data.key

%d+ is a string pattern. %d matches any number, and + will match as many as the flag (in this case, a number) in a row.

1 Like

Thank you for the solution. I found something similar on another post but never tried it anyways… Thank you so much and have a nice day :wink:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.