views:

114

answers:

2

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

When I have this checking in it, 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 documenatiton, sort function should return false, if a goes after b. True otherwise.

If I remove remove that code, it of course crashes of indexing nils.

+1  A: 

To 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 the 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
Long Cheng
Sorry I guess I didn't explained myself well enough: First, THERE'S NO NIL IN TABLE. Second, table.sort doesn't want to have so many conditions there clearly, because when I remove nil checking it continues, but crashes o nil.
mnn
+4  A: 

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

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).

In other words, comp(a,b) must imply not comp(b,a). If this relation does not hold, then the error "invalid order function for sorting" will likely raised. (Note that it might not be raised in all cases.)

In order to be more helpful, we really need to see the whole function passed to table.sort.

RBerteig
+1: After testing the code from the question, it does handle nil values in an array correctly. The problem must be inconsistency in the remainder of the function.
gwell