0%

Lua排序

Value排序

Lua 中table.Sort(table, fun) or table.Sort(t)

  • 不稳定排序 -快排
  • 连续数组
  • 默认小于(升序)排
1
2
local test_table = {2,1,3}
local teas_table = {{3, b = "3"},{c = "", b = 4},{b = 5}}
1
2
3
4
5
6
7
8
9
10
11
12
table.sort(teas_table, funtion(x, y){
return tostring(x.b) < tostring(y.b)
// 不能带 =:如 >= | <=
// 带报错:attempt to compare number with nil和invalid order function for sorting
// 原因:比较函数需要满足非对称和传递性质


if a.level ~= b.level then
return a.level > b.level
end
return a.exp > b.exp
})

Note that the comp function must define a strict partial order over the elements in the list; that is, it must be asymmetric and transitive. Otherwise, no valid sort may be possible.

http://www.lua.org/source/5.1/ltablib.c.html

报错位置 *for (;;) { */\ invariant: a[l..i] <= P <= a[j..u] */* **

可以看到是边界判断的地方出了问题。假定传入的排序函数在遇到a == b 的时候返回false,因而底层的排序函数没有对这种情况进行严格的边界检查。

Key排序

取key放入新表,排序。然后映射。

1
2
3
4
5
6
7
8
9
10
11
local test1 ={a=1,f=9,d=2,c=8,b=5}

local key_test ={}
for i in pairs(test1) do
table.insert(key_test,i) --提取test1中的键值插入到key_test表中
end

table.sort(key_test)
for i,v in pairs(key_test) do
print(v,test1[v])
end

https://blog.csdn.net/coffeecato/article/details/79117700

http://pkxpp.github.io/2016/07/26/lua%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0(6)table.sort/

https://blog.csdn.net/David_Dai_1108/article/details/46434787