lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Michel Machado wrote:

> table.sort(t,
>   function (a, b)
>     assert(a ~= nil, "left var is nil!")
>     assert(b ~= nil, "right var is nil!")
>     return not (a < b) -- I want an inverted sort!
>   end)

I've done this exact same thing.  The reference manual says:

# If comp is given, then it must be a function that receives
# two table elements, and returns true when the first is
# less than the second (so that not comp(a[i+1],a[i]) will
# be true after the sort).

A not-so-obvious corollary is that the function has to
return false if the two items are equal.  The sort algorithm
depends on this being true and does weird stuff if it's not
true.  Instead use "return a > b" as suggested by Virgil
Smith.

(And don't feel bad -- it took me a couple days to figure
this out when it happened to me.)

-- 
Aaron