I am trying to make a following npc, but my find closest player script is not working as expected.

It seems that the distance is being set to nil, as when i return distance from my function, it prints nil.

I have a beginner to intermediate understanding of Lua and Roblox, but I have no idea whats going wrong.

Here is my code (from a serverside script, if that helps):

playerList = game.Players:GetPlayers()
part = script.Parent.Torso

function findClosestPlayer(originPart, players, maxDistance)
	local closestPlayer
	local mindistance = maxDistance
	for _, playerToFind in ipairs(players) do
		local distance = (originPart.Position - playerToFind.Character.Torso.Position).magnitude
		if distance < mindistance then
			closestPlayer = playerToFind
			mindistance = distance
		end
	end
	
	if closestPlayer then
		print(closestPlayer)
		return closestPlayer
	end
end

while true do
	playerList = game.Players:GetPlayers()
	wait(5)
	chosenPlayer = findClosestPlayer(part, playerList, 100)
	print(chosenPlayer)
end