Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How does the second parameter of table.sort (comp) work?

Will learning about it, I got really confused about it. All I'm just asking is how to use.

2 answers

✓ Accepted answer

The second parameter of table.sort() is called a comparator function. It is called with two arguments representing two elements from the array and the comparator function is supposed to return a bool (truthy/falsey value) representing whether or not the first element should go after the second element. Because functions are first class values in Lua, you can simply pass in a function in the parameter list like any other value. Here are a few examples:

--Sort numbers in ascending order
local table1 = {3 , 4 , 2 , 1 , 4}

table.sort(table1 , function(a , b)
	return a < b
end)

--Note: equivalent to table.sort(table1) because the default comparator is used


--Another slightly less trivial example
--Sorts the leaderboard points in descending order
local leaderstats = {
	{Name = "Player1"; Points = 100};
	{Name = "Player3"; Points = 300};
	{Name = "Player5"; Points = 200};
	{Name = "RayCurse"; Points = 500};
	{Name = "iofkl"; Points = 600};
}

table.sort(leaderstats , function(a , b)
	return a.Points > b.Points
end)

I can recommend looking at lua-users.org. The comp parameter is a function that takes 2 arguments and returns true if the first one should be sorted before and vice versa. Example:

t = { 3,2,5,1,4 }
table.sort(t, function(a,b) return a>b end)
-- The table will now look like this { 5,4,3,2,1 }

6 comments

0

So basically if it returns true, a will be first?

0

Yes, if it returns true a will be placed before b, the condition can be anything.

0

And if false then b will be placed first?

0

Correct

0

table.sort sorts the table in place so there is no need to reassign the variable.

0

Ah yes, my bad. You are correct, will fix the code example.

This discussion is preserved as it was. New answers, comments, and votes are closed.