Lua表格排序声称排序函数无效

7

我目前正在使用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

所有元素值都是数字,因此根据我的理解,比较函数的要求已经满足了,但也许我的想法有误(这基本上就是问题所在,即为什么或在什么情况下以上内容可能导致无效的排序函数错误)。

遗憾的是,这个错误很难被分离出来,并且只在一个案例中发生过,而且只有在代码成功完成了很多排序之后才会发生。因此,作为第一步,我想确保我没有完全忽略了类似上面的函数中明显错误的东西。


1
考虑对于 a = {totalfilll = 1, totalfill = 2}; b = {totalfilll = 2, totalfill = 1};sort_list_function(a,b)sort_list_function(b,a) 的结果。 - Colonel Thirty Two
@ColonelThirtyTwo 谢谢,所以可能害怕是正确的,需要我抛光我的弹珠,所以有一种方法可以在一个简单的例子中使两个方向都为真,我只是没看到。 - Frank Mittelbach
2个回答

7

好的,感谢@ColonelThirtyTwo的提示,答案是比较函数确实有误,我需要明确处理>情况,并立即返回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   

1
我发现易于理解的比较的替代方法。
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接