Table.sort function is erroring why?

I’m trying to make a “Equip Best” for my simulator game and the table.sort function is erroring saying
“invalid order function for sorting”.

Code:

local function EquipBest()
	UnequipAll()
	local tbl1 = {}
	local tbl2 = {}
	
	for i, v in pairs(Pets:GetChildren()) do
		local PetLevel = v:FindFirstChild("Level")
		tbl1[i] = v.Name
		tbl2[v.Name] = PetLevel.Value
	end
	
	table.sort(tbl1, function(a,b)
		local a1 = tbl2[a]
		local b1 = tbl2[b]
		
		if a1 == nil then return false end
		if b1 == nil then return false end
		
		if a1 > b1 then
			return true
		end
		if b1 > a1 then
			return true
		end
		if b1 == a1 then
			return true
		end
	end)
	
	for i = 1, max, 1 do
		Event:FireServer("EquipPet", tbl1[i])
	end
end

Any help is appreciated

1 Like

The function you give to table.sort has to consistently return something < somethingElse otherwise the sorting algorithm gets confused about the order of things.

Luckily this is a simple fix for you; instead of nil checks, you can give a default value, which means you just need one comparison:

    table.sort(tbl1, function(a,b)
		local a1 = tbl2[a] or 0 -- default value, change if you want
		local b1 = tbl2[b] or 0
		
		return a1 < b1
	end)
3 Likes

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