Attempt to compare table < table

I’m trying to sort a table from largest to smallest, but it doesn’t work and I get the following error in the output: attempt to compare table < table

Code:

print(table.sort(roles))
1 Like

What is inside the roles table?

local Table = {
	[1] = {
		["id"] = 70148314,
		["memberCount"] = 0,
		["name"] = "Guest",
		["rank"] = 0
	},
	[2] = {
		["id"] = 70148313,
		["memberCount"] = 2224,
		["name"] = "Basic Membership",
		["rank"] = 1
	},
	[3] = {
		["id"] = 70149008,
		["memberCount"] = 0,
		["name"] = "Premium+",
		["rank"] = 100
	},
	[4] = {
		["id"] = 70521705,
		["memberCount"] = 2,
		["name"] = "Contributor",
		["rank"] = 150
	},
	[5] = {
		["id"] = 70275755,
		["memberCount"] = 1,
		["name"] = "Moderator",
		["rank"] = 240
	},
	[6] = {
		["id"] = 70521542,
		["memberCount"] = 0,
		["name"] = "Head Moderator",
		["rank"] = 245
	},
	[7] = {
		["id"] = 70148312,
		["memberCount"] = 1,
		["name"] = "FPA Management",
		["rank"] = 250
	},
	[8] = {
		["id"] = 70169386,
		["memberCount"] = 0,
		["name"] = "Owner",
		["rank"] = 254
	},
	[9] = {
		["id"] = 70148311,
		["memberCount"] = 1,
		["name"] = "Holder",
		["rank"] = 255
	}
}

The default sort function compares the values inside the table. It compares a table with a table, and since they don’t have metatables, it errors. What exactly do you want to sort the ranks by?

I want to sort them by rank (0-255)

table.sort doesn’t return anything, so that will always print nothing

To sort your table by rank from largest to smallest you can pass a custom compare function to table.sort like so

table.sort(Table, function(A, B)
	return A.rank > B.rank
end)

1 Like