Re: table.sort: invalid order function for sorting
"'Martin Eden' via lua-l" <[email protected]> Fri, 24 Apr 2026 18:15:56 +0200
| Newsgroups | gmane.comp.lang.lua.general |
|---|---|
| Message-ID | <[email protected]> |
On 2026-04-24 17:28, 'Lars Müller' via lua-l wrote: > You can easily invert sorting. You just swap the two arguments: > > table.sort(Orders, function(a, b) return DateIsLess(b, a) end) That's right. Came to that after 40 seconds since I sent email. But we can't say it's obvious, right? Besides, in real life there will be several lines of code instead of "a, b". > Also not sure I get your point about needing to implement both "less > than" and "is equal". > "Less than" suffices, you can default "is equal" to "not (lt(a, b) or > lt(b, a))". > > Needing two "comparator" calls to decide equality may of course not be > ideal for runtime, > but tends to be fine since it usually just adds a constant factor of > about ~2 at worst. Time spent in comparator is not limited. So sorting time may consist mostly of time in that function. Imagine we're doing web request for each comparison.. Imagine two times longer line of people in every shop you visit.. > I think having comparators be boolean "less than" functions makes some > sense though. > I want to be able to just write something like table.sort(t, > function(a, b) return a > b end). > > Introducing a kind of "spaceship operator" seems like too much for a > simple scripting language like Lua. > What would the type of the result be? You could make it a number, of > course, but that's really a hack. > (And one that tends to produce bugs when you have integer wraparound, > which Lua does.) > I prefer the boolean-typed result of a "less than" comparison. > (I contemplated "lt(a, b)" evaluating to nil if they a == b as a > convention for comparators, > which would mostly still keep things working as nil is falsey, but > that's also hacky.) Yeah it's hacky. But I agree that we need some three-ways binary operator for scalar comparisons. Boolean "less than" is perfectly fine. Problem that comparisons are costly. So we spent like 24800 microseconds just to get data. And then compare numbers and return 0 or 1. Which takes like 20 micros. Ideally comparator should provide as much information about relation of given items as it can. At least three output values if there is linear order. What sorting algorithm will do with them is his own business. > > - Lars -- Martin -- You received this message because you are subscribed to the Google Groups "lua-l" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion visit https://groups.google.com/d/msgid/lua-l/c92932db-6e2c-46e6-8bc2-c020834d9bff%40disroot.org.