[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Sort problem
- From: Michel Machado <michel@...>
- Date: Mon, 26 Jul 2004 15:31:34 -0300
Dears,
I think that this comment could be added to the Lua manual.
Thanks Aaron!
[ ]'s
Michel Machado
On Mon, 2004-07-26 at 14:45, Aaron Brown wrote:
> 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.)