Lua踩坑日志
2021-9-17 Lua自定义排序Sort中的坑 两个值相同的时候不能返回True
1、table.sort是排序函数,它要求要排序的目标table的必须是从1到n连续的,即中间不能有nil;
2、当比较函数没有写的时候,table.sort默认按照lua里面的排序规则升序排序;当额外写了比较函数时,这就有一个特别要注意的问题,当两个数相等的时候,比较函数一定要返回false!
如果排序函数返回true
时则会 invalid order function for sorting的错误。但是这个报错不一定会立马暴露出来,如果不注意就会埋了一个雷,只有当table中同时存在多个值相同的时候会报错。
local function SortFunc(a, b) return a["score"] < b["score"] end table.sort(soulCards, SortFunc)
下面是table.sort的源码
static int sort (lua_State *L) { lua_Integer n = aux_getn(L, 1, TAB_RW); /* 检查第一个参数是否为合法有序的Table并获取Table长度 */ if (n > 1) { /* non-trivial interval? */ luaL_argcheck(L, n < INT_MAX, 1, "array too big"); /* 检查Table长度是否合法 */ if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? 检查是否有第二个参数 */ luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function 检查第二个参数是否为正确的排序方法 */ lua_settop(L, 2); /* make sure there are two arguments 只取方法的前两个参数*/ auxsort(L, 1, (IdxT)n, 0); /* 快速排序算法*/ }
Lua 5.3 参考手册 http://cloudwu.github.io/lua53doc/contents.html
Lua源码使用方法 来自 阿龙12345 https://www.cnblogs.com/chenlong12345/p/14405599.html