Attempt to index nil with number

Hello. I have a table that saves the player name and a certain IntValue into it and filters players from highest to lowest so it chooses the player with the highest value to put onto an “employee of the month” poster. Issue is that the function is returning nil. Is it because the function is wrong or what? I’m not sure how to fix this as everything seems fine to me.

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.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)

	local id = player.UserId
	local ThumbType = Enum.ThumbnailType.HeadShot
	local ThumbSize = Enum.ThumbnailSize.Size150x150
	local plrAvatar, isReady = Players:GetUserThumbnailAsync(id, ThumbType, ThumbSize) 
	ImageLabel.Image = plrAvatar 
	PlayerName.Text = player.Name
end

Players.PlayerAdded:Connect(onPlayerAdded)

while true do
	local employeeOfTheMonthData = ReturnEmployeeOfTheMonth()
	print("Player: ".. employeeOfTheMonthData[1])
	print("Amount earned: ".. employeeOfTheMonthData[2])

	task.wait(10)
end

local employeeOfTheMonth = ReturnEmployeeOfTheMonth()
print(employeeOfTheMonth)

image
Explorer picture

Any and all help is very much appreciated.

Your script is likely running before anyone is able to join the game. To avoid this error, check to see if employeeOfTheMonthData is nil.

while true do
	task.wait(10)
	local employeeOfTheMonthData = ReturnEmployeeOfTheMonth()
	if not employeeOfTheMonthData then
		continue;
	end
	print("Player: ".. employeeOfTheMonthData[1])
	print("Amount earned: ".. employeeOfTheMonthData[2])
end
2 Likes

I applied your fix and it doesn’t throw up any errors anymore. Thank you so much!

1 Like

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