Sorting a table of pets by the most powerful to the lowest one!

Hey guys!

I’m making an inventory!

I’m trying to change the LayoutOrder of my templates to put the equipped one on the top of the inventory and sort them to the most powerful to the lowest one.

So this is what i excpect to do:

table.sort(nonConcerned, function(a,b)
		return (a.Power.Value > b.Power.Value)
	end)

It seems to be working sometimes but sometimes the inventory messed up and some pets are not where they are supposed to be.

I think it comes from the table.sort function.

So, here is the full function:

local function LayoutOrder()
	local concerned = {}
	local nonConcerned = {}
	for _, v in pairs(ScrollingFrame:GetChildren()) do
		if v:IsA("TextButton") then
			if v:FindFirstChild("Equipped").Value then
				table.insert(concerned, v)
			else
				table.insert(nonConcerned, v)
			end
		end
	end
	
	for i, template in pairs(concerned) do
		if template then
			template.LayoutOrder = 1
		end
	end
	
	table.sort(nonConcerned, function(a,b)
		return (a.Power.Value > b.Power.Value)
	end)
	
	local counter = 2
	for _, v in pairs(nonConcerned) do
		v.LayoutOrder = counter
		counter = counter + counter
	end
end

How can I fix that?

1 Like

Just change the layout order to the negative value of the pet’s power. You don’t need to sort anything

This is a good way to make this, but it doesn’t work for storing the equipped pets on the top of the inventory.

I just find a nice issue:

---- LayoutOrder() Functon() ----
local function LayoutOrder()
	-- Get all equipped pets --
	local equipped = {}
	local unequipped = {}
	for _, tp in pairs(scrollingFrame:GetChildren()) do
		if tp:IsA("TextButton") and tp.Equipped.Value then
			table.insert(equipped, tp)
		elseif tp:IsA("TextButton") then
			table.insert(unequipped, tp)
		end
	end

	table.sort(equipped, function(a,b)
		return (a.Power.Value > b.Power.Value)
	end)

	table.sort(unequipped, function(a,b)
		return (a.Power.Value > b.Power.Value)
	end)
	
	local counter = 1
	for _, v in pairs(equipped) do
		v.LayoutOrder = counter
		counter = counter + 1
	end

	for _, v in pairs(unequipped) do
		v.LayoutOrder = counter
		counter = counter + 1
	end
end

Here is the solution I am using if you want!

Bye!