在排序函数中处理 nils

发布于 2024-08-18 08:32:36 字数 308 浏览 2 评论 0原文

我不知道如何处理我的排序函数得到的 nils

当我进行此检查时,table.sort 在一些调用后崩溃。

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

出现此错误:排序功能无效。但根据文档,如果 a 在 b 之后,排序函数应该返回 false。否则确实如此。

如果我删除删除该代码,它当然会因索引为零而崩溃。

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 documentation, 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

随梦而飞# 2024-08-25 08:32:36

这与表中的 nil 值几乎没有关系。如果比较函数本身无效,则会生成错误消息。来自 table.sort< 的文档/a>:

如果给出了 comp,那么它必须是
接收两个表的函数
元素,并且当
第一个小于第二个(因此
not comp(a[i+1],a[i]) 将为 true
排序后)。

换句话说,comp(a,b) 必须暗示不是 comp(b,a)。如果此关系不成立,则可能会出现错误“排序函数无效”。 (请注意,它可能不会在所有情况下都会引发。)

为了更有帮助,我们确实需要查看传递给 table.sort 的整个函数。

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.

感受沵的脚步 2024-08-25 08:32:36

将所有 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文