Zero handling in sorting

I don't know how to handle nils my sort function gets.

When I have this check, table.sort crashes after some calls.

 if a == nil then return false elseif b == nil then return true end 

With this error: Invalid order function for sorting . But according to the documentation, the sort function should return false if a comes after b. Otherwise.

If I delete this code, delete it from scratch.

+4
source share
2 answers

This has little or nothing to do with the nil values ​​in the table. An error message is generated if the comparison function itself is invalid. From the documentation for table.sort :

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

In other words, comp(a,b) should mean not comp(b,a) . If this relation is not satisfied, then the error “incorrect order function for sorting” is likely to be raised. (Note that in all cases this may not be raised.)

To be more useful, we really need to see that the entire function is passed to table.sort .

+12
source

Put all nil values ​​at the beginning of the array:

  function mycomp(a,b) if a == nil and b == nil then return false end if a == nil then return true end if b == nil then return false end return a < b end 

To put all nil values ​​at the end of an array:

 function mycomp(a,b) if a == nil and b == nil then return false end if a == nil then return false end if b == nil then return true end return a < b end 
+2
source

All Articles