Using table.sort() to sort values from highest to lowest

In simple, I’m looking to sort a table by an integer (highest to lowest) contained within the arrays of a table.

I had a go below, but couldn’t quite get it to work:

local tableToSort = {
	{"Player1", 2};
	{"Player2", 1};
	{"Player3", 3};
	}

local sortedTable = table.sort(tableToSort,
	function(a,b)
		return a[2] > b[2]
	end
	)

for i,v in pairs(sortedTable) do
	print(v[1].." | "..v[2])
end

Desired output:

Player 3 | 3
Player 1 | 2
Player 2 | 1

20 Likes

table.sort doesn’t return a table, it sorts the table that is passed.

47 Likes

It looks like you fixed it.

1 Like

I tested out the code you provided and it printed the desired output you wanted. What is the issue here?

1 Like