Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 5 years ago

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

2 answers

Log in to vote
0
Answered by
RayCurse 1518 Moderation Voter
5 years ago
Edited 5 years ago

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)

Ad
Log in to vote
0
Answered by
gullet 471 Moderation Voter
5 years ago
Edited 5 years ago

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 }
0
So basically if it returns true, a will be first? User#24541 10 — 5y
0
Yes, if it returns true a will be placed before b, the condition can be anything. gullet 471 — 5y
0
And if false then b will be placed first? User#24541 10 — 5y
0
Correct gullet 471 — 5y
View all comments (2 more)
0
table.sort sorts the table in place so there is no need to reassign the variable. RayCurse 1518 — 5y
0
Ah yes, my bad. You are correct, will fix the code example. gullet 471 — 5y

Answer this question