【问题标题】:Lua table sort claims invalid order function for sortingLua table sort声称排序功能无效
【发布时间】:2021-08-08 04:53:53
【问题描述】:

我目前在 LuaTeX(这是一个带有内置 lua 解释器的 TeX 引擎)中有一个更大的程序,并且在程序的一部分中对表格进行了排序。表格元素本身就是具有一定结构的表格,排序功能如下:

function sort_list_function (a,b)

  if a.totalfilll < b.totalfilll then
    return true
  elseif a.totalfill < b.totalfill then
    return true
  elseif a.totalfil < b.totalfil then
    return true
  elseif a.totalvalue + a.height + a.totalplus <
         b.totalvalue + b.height + b.totalplus
  then   
    return true
  else
    return false
  end       
end

所有元素值都是数字,所以据我了解,比较功能的要求已经满足,但也许我的想法在这里偏离了(这基本上是一个问题,即,为什么或在什么情况下,上述结果会导致无效订单功能错误)。

不幸的是,该错误很难隔离,并且仅在一次情况下发生,然后仅在代码成功完成很多次之后才发生,因此作为第一步,我想确保我没有完全清楚地遗漏某些东西上面的函数有问题。

【问题讨论】:

  • 提示:考虑sort_list_function(a,b)sort_list_function(b,a) 对于a = {totalfilll = 1, totalfill = 2}; b = {totalfilll = 2, totalfill = 1}; 的结果
  • @ColonelThirtyTwo 谢谢,所以可能担心是对的,需要我的弹珠抛光,所以在一个简单的例子中,有办法让两个方向都正确,我只是没看到

标签: sorting lua


【解决方案1】:

好的,感谢@ColonelThirtyTwo 的提示,答案是比较函数确实是错误的,我也必须明确处理&gt; 的情况并立即返回false(在我的情况下,不同的测试意味着具有不同的重要性顺序)例如,像

  if a.totalfilll < b.totalfilll then
    return true
  elseif a.totalfilll > b.totalfilll then
    return false
  elseif a.totalfill < b.totalfill then
    return true
  elseif a.totalfill > b.totalfill then
    return false
  elseif a.totalfil < b.totalfil then
    return true
  elseif a.totalfil > b.totalfil then
    return false
  else
    return ( a.totalvalue + a.height + a.totalplus <
             b.totalvalue + b.height + b.totalplus    )
  end   

【讨论】:

    【解决方案2】:

    我觉得很容易理解的另一种比较方法。

    function sort_list_function (a,b)
      if a.totalfilll ~= b.totalfilll then
        return a.totalfilll < b.totalfilll
      elseif a.totalfill ~= b.totalfill then
        return a.totalfill < b.totalfill
      elseif a.totalfil ~= b.totalfil then
        return a.totalfil < b.totalfil
      else
        return ( a.totalvalue + a.height + a.totalplus <
                 b.totalvalue + b.height + b.totalplus )
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 2021-09-03
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多