Lua踩坑日誌
阿新 • • 發佈:2021-09-17
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原始碼使用方法 來自阿龍12345https://www.cnblogs.com/chenlong12345/p/14405599.html