Re: table.sort: invalid order function for sorting
Halalaluyafail3 <[email protected]>
| Newsgroups | gmane.comp.lang.lua.general |
|---|---|
| Message-ID | <[email protected]> |
On Friday, April 17, 2026 at 8:55:59 AM UTC-4 Martin Eden wrote:
Hello guys,
I've just found unobvious thing about table.sort:
-- ! invalid order function for sorting
table.sort({ 1, 2, 3, 1 }, function(a, b) return (a <= b) end)
Lua manual says:
The comp function must define a consistent order; more formally, the
function must define a strict weak order. (A weak order is similar to
a total order, but it can equate different elements for comparison
purposes.)
and for me <= operator is weak order.
The usual definition of strict weak orders does not permit this. In
particular the comparison function should be irreflexive (f(x,x) is always
false), asymmetric (f(x,y) being true implies f(y,x) is false), transitive
(f(x,y) being true and f(y,z) being true implies f(x,z) is true), and
transitive for values that compare equal (all of f(x,y), f(y,x), f(y,z),
and f(z,y) being false implies f(x,z) and f(z,x) are both false). The
comparison function here is reflexive (ignoring NaN) and not asymmetric, so
it is not valid.
Practically it means that table.sort() never passes same item
to comparator and when writing comparisons explicitly,
default is "false":
local compare =
function(a, b)
if (a < b) then return true end
if (a > b) then return false end
return false
end
return a<b
This error is not stable for my use case with comparing tables.
"return false" default eliminates it but sometimes "return true"
works too.
Bug?
I do not see a bug here. Though it will not always diagnose a bad ordering.
-- 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/382e8f58-3492-4ba7-b1f7-174b8306266en%40googlegroups.com.