在排序函数中处理空值

我不知道如何处理排序函数中的 nil 值。当我在函数中加上下面的检查代码后,table.sort 在经过一些调用后就会崩溃。

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

出现错误:无效的排序函数。但依据文档,排序函数应该在 a 来在 b 后时返回 false,否则返回 true。

如果我移除上面代码,当然它就会因索引 nil 导致崩溃。

原文链接 https://stackoverflow.com/questions/2102710

点赞
stackoverflow用户229744
stackoverflow用户229744

将所有的nil值放在数组的开头:

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

将所有的nil值放在数组的结尾:

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
2010-01-20 16:38:02
stackoverflow用户68204
stackoverflow用户68204

这与表中的 nil 值几乎没有任何关系。错误消息是在比较函数本身无效时生成的。来自table.sort的文档:

如果提供了 comp,那么它必须是一个 函数,该函数接收两个表 元素,并在第一个小于第二个时返回 true (因此 not comp(a[i+1],a[i]) 在排序后为真)。

换句话说,comp(a,b)必须意味着not comp(b,a)。如果这个关系不成立,那么错误“invalid order function for sorting”可能会被提出。 (请注意,它可能不在所有情况下都提出。)

为了提供更有效的帮助,我们真的需要看到传递给table.sort的整个函数。

2010-01-21 23:48:48