[置顶] Lua中table.sort() 报错 attempt to compare number with nil和invalid order function for sorting

table.sort() 
table.sort(table_name, sortFunc)

programming in Lua (First edition)的说明:
http://www.lua.org/pil/19.3.html
This order function receives two arguments and must return true if the first argument should come first in the sorted array.

#table.sort()函数对给定的table进行升序排序.
#sortFunc是一个可选的参数, 此参数是一个外部函数, 可以用来自定义sort函数的排序标准.此函数可以被省略。

#sortFunc应满足以下条件: 接受两个参数(依次为a, b), 并返回一个布尔型的值, 当a应该排在b前面时, 返回true, 反之返回false.

注意:对于 a==b 的情况,一定要返回 false 不然会出现以下错误
error:attempt to sortFuncare number with nil 
error:invalid order function for sorting 


我们看下Lua实现快速排序的代码
http://www.lua.org/source/5.1/ltablib.c.html

    
for (;;) {  /* invariant: a[l..i] <= P <= a[j..u] */
  /* repeat ++i until a[i] >= P */
  while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) {
    if (i>u) luaL_error(L, "invalid order function for sorting");
    lua_pop(L, 1);  /* remove a[i] */
  }
  /* repeat --j until a[j] <= P */
  while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) {
    if (j<l) luaL_error(L, "invalid order function for sorting");
    lua_pop(L, 1);  /* remove a[j] */
  }
  if (j<i) {
    lua_pop(L, 3);  /* pop pivot, a[i], a[j] */
    break;
  }
set2(L, i, j);
}



# 如果 a==b 时返回 true 且边界上的几个值是相等的话, sort_sortFunc 就无法阻止 i 继续增长,直到超出边界引发异常 attempt to sortFuncare number with nil;
# 即使我们对 a 和 b 进行非空判断,也会因为 i 超过边界而引发异常 invalid order function for sorting 

你可能感兴趣的:(lua,bug)