How do you use table.sort?

I know what it’s for, but how do I use it?

4 Likes

As per Lua specification, table.sort works as follows:

table.sort(Table t, Predicate p = default)
The object t is a Lua table you want sorted, and p is an optional Lua function you can pass for doing the comparisons.

sort iterates over all the items in t and runs p(a, b) on them. p returns true if a should come before b. The table is sorted in place, so t can be modified after the call to sort.

If you don’t provide a function for the p argument, a default is used, which behaves something like this:

local function pred(a, b)
    return a < b
end

Note that if you pass a p predicate, you’ll have to make sure p(a, b) ~= p(b, a), that is to say your results should be consistent back and forth on which item comes before the other.

57 Likes