Dictionary seems to be recognized as empty?

I’m trying to make a chase system for a NPC, although It seems the contents from the Magnitudes dictionary seem to be recognized as nil.

local PFS = game:GetService('PathfindingService')
local NPC = script.Parent
local Hum = NPC:FindFirstChild('Humanoid')
local HRP = NPC:FindFirstChild('HumanoidRootPart')
local Players = game:GetService('Players')

function GetNearestHRP()
	local NearestCharacter
	
	local function GetMagnitudes()
		local Magnitudes = {}
		
		for _, Player in pairs(Players:GetPlayers()) do
			local Character = Player.Character or Player.CharacterAdded:Wait()
			local CharHRP = Character:FindFirstChild('HumanoidRootPart')
			
			if CharHRP then
				print('Has humanoid root part')
				Magnitudes[Player.Name] = (CharHRP.Position - HRP.Position).Magnitude
				print(Magnitudes[Player.Name])
			end
		end
		
		
		return Magnitudes
	end
	
	local Magnitudes = GetMagnitudes()
	
	local function GetNearestCharacterName()
		for PlrName, Magnitude in pairs(Magnitudes) do
			if math.min(table.unpack(Magnitudes)) == Magnitude or #Players:GetPlayers() == 1 then -- :33: missing argument #1 to 'min' (number expected)
				return PlrName
			end
		end
	end
	
	NearestCharacter = Players:FindFirstChild(GetNearestCharacterName()).Character or Players:FindFirstChild(GetNearestCharacterName()).CharacterAdded:Wait()
	
	return NearestCharacter:FindFirstChild('HumanoidRootPart')
end

function SetupPathfinding(Origin, End)
	local Path = PFS:CreatePath()
	Path:ComputeAsync(Origin, End)
	local Waypoints = Path:GetWaypoints()
	
	for _, Waypoints in pairs(Waypoints) do
		Hum:MoveTo(Waypoints.Position)
	end
end

while wait(1) do
	local Succ, NearestHRP = pcall(GetNearestHRP)
	
	if Succ and NearestHRP then
		SetupPathfinding(HRP.Position, NearestHRP.Position)
	else
		print(NearestHRP) -- :33: missing argument #1 to 'min' (number expected)
	end
end

The part print(NearestHRP) (Which after some checks, supposedly is a error) prints that the argument #1 of math.min is missing, although it shouldn’t be, because I passed Magnitudes but unpacked.

Suggestions to improve the code are also welcome.

1 Like

After testing, it seems table.unpack returns nothing if the given parameter is a dictionary. Any wonders what to do?

Edit: Why do I only think correctly when I make a post? WHAT’S GOING ON WITH ME?!?!

Solution to the post:

Table.unpack seems to not unpack a table when it’s a dictionary. And so, this is what I did:

function Unpack(Table)
	local Returning = {}
	
	for Key, Value in pairs(Table) do
		table.insert(Returning, Value)
	end
	
	return table.unpack(Returning)
end

What does this do is: It gets all the values from the given table, and inserts it into other table, basically converting the given table into an array, and so, we return that table but unpacked - using the built-in unpack function. (table.unpack)

3 Likes