How can I sort a table's value's names?

I have an extremely simple script that creates a table and puts 3 TextLabels inside of it. The TextLabel’s names are 1,2 and 3 so I would like to sort the table as the names of the TextLabels but I’m not sure how to do that. If I were to just sort the TextLabels themselves I get this error: attempt to compare Instance.

I’m not sure how to do this but if someone could help me that would be greatly appreciated! Thanks!


local SlotsAvailable = {}

for i,v in pairs(script.Parent.InventoryFrame.Slots:GetChildren()) do
	local Slot = v
	table.insert(SlotsAvailable, Slot)

You need to tell Lua(u) that you want to sort based on the name.

local SlotsAvailable = {}

for _, Slot in pairs(script.Parent.InventoryFrame.Slots:GetChildren()) do
	table.insert(SlotsAvailable, Slot)

table.sort(Slots, function(a, b)
    return tonumber(a.Name) < tonumber(b.Name)

This will sort the table in ascending order based on the names of the text labels.

1 Like

You need to add a function that tells table.sort how to sort, as the 2nd parameter.

Read this post for a good explanation: