Table doesn't update properly

Hello. Once again I’m having issues with a script. This script fetches the data of all players present (name, id and an IntValue) and puts it into a table, sorts it, prints the player with the highest of that value. Then it returns the table and saves it as a function. Then every 10 seconds it updates the ImageLabel and TextLabel with the player that gets printed as the employeeOfTheMonth table. Or at least that’s what it should be doing. Instead it sets the ImageLabel and ImageText to the newest player that joined the game, unsure as to why as everything in the .PlayerAdded function seems fine.

TLDR: ImageLabel and TextLabel are set for the newest player in server, not the player that’s saved in the table

local Players = game:GetService("Players")

local ImageLabel = script.Parent
local PlayerName = script.Parent.Parent.PlayerName

local function ReturnEmployeeOfTheMonth()
	local playerTable = {}

	for i, player in ipairs(Players:GetPlayers()) do
		table.insert(playerTable, {
			player.Name,
			player.UserId,
			player.BrickCount.BrickCountValue.Value
		})
	end

	table.sort(playerTable, function(a, b)
		return a[2] > b[2]
	end)
	return playerTable[1]
end

local function onPlayerAdded(player)
	local intValue = player.BrickCount.BrickCountValue 

	intValue.Changed:Connect(function()
		local employeeOfTheMonth = ReturnEmployeeOfTheMonth()
		print(employeeOfTheMonth)
	end)
end

Players.PlayerAdded:Connect(onPlayerAdded)

while true do
	task.wait(10)
	local employeeOfTheMonthData = ReturnEmployeeOfTheMonth()
	if not employeeOfTheMonthData then
		continue;
	end
	local id = employeeOfTheMonthData[2]
	local ThumbType = Enum.ThumbnailType.HeadShot
	local ThumbSize = Enum.ThumbnailSize.Size150x150
	local plrAvatar, isReady = Players:GetUserThumbnailAsync(id, ThumbType, ThumbSize)
	ImageLabel.Image = plrAvatar
	PlayerName.Text = employeeOfTheMonthData[1]
	print(employeeOfTheMonthData)
end
local employeeOfTheMonth = ReturnEmployeeOfTheMonth()
print(employeeOfTheMonth)

image

Any help and tips are very much appreciated.

For some reason, the table doesn’t seem to update with the correct player, instead it keeps printing out whatever the latest player joined and their saved values.
image
Keeps printing out Player1 despite Player2 having a higher value than them. No I did not edit the values with studio. What’s the issue?

1 Like

It looks like you are comparing the userId, not their value. In lua, table indexes start at 1 not 0.

1 Like

Oh, oops. Added that line in and forgot to adjust the rest of the code. Thank you so much.

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