lua table.srot()
lua 的table.srot()函数使用了ipairs的遍历机制,所以要求要排序的table的key从一开始顺序排列。否则结果会千奇百怪,而且每次结果不是稳定的。table.srot()允许用户自定义排序方式,但是不能是不确定排序,及不允许相等时返回true,否则会陷入死循环报错。因为是返回true时就交换位置。table.srot()内部是快速排序。
非ipairs:
local table_s = {[2]="a",[3]="c",[4]="b"}
table.sort(table_s)
for i,v in pairs(table_s) do
print(i,v)
end
结果:
4 b
2 a
3 c
[Finished in 0.1s]
正确例子:
local table_s = {"a","c","b"}
table.sort(table_s)
for i,v in ipairs(table_s) do
print(i,v)
end
结果:
1 a
2 b
3 c
[Finished in 0.1s]
自定义排序例子:
local table_s = {"a","c","b"}
table.sort(table_s,function (m,n)
return m>n
-- body
end)
for i,v in ipairs(table_s) do
print(i,v)
end
结果:
1 c
2 b
3 a
[Finished in 0.1s]
不稳定排序:不稳定排序的报错,是要出现在数组中有两个相同的元素的情况下。
local table_s = {"a","c","b","b"}
table.sort(table_s,function (m,n)
return m >= n
-- body
end)
for i,v in ipairs(table_s) do
print(i,v)
end
结果:
C:/Users/DELL/Downloads/lua-5.3.4_Win64_bin/lua: C:\Users\DELL\Desktop\lua_test\contine:55: invalid order function for sorting
stack traceback:
[C]: in function 'table.sort'
C:\Users\DELL\Desktop\lua_test\contine:55: in main chunk
[C]: in ?
[Finished in 0.1s with exit code 1]
[cmd: ['C:/Users/DELL/Downloads/lua-5.3.4_Win64_bin/lua', 'C:\\Users\\DELL\\Desktop\\lua_test\\contine']]
[dir: C:\Users\DELL\Desktop\lua_test]
[path: C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Users\DELL\Downloads\lua-5.3.4_Win64_bin;C:\Users\DELL\AppData\Local\Microsoft\WindowsApps]
那么如果我们一定要使用,非ipirs结构进行排序又要怎么办呢?
这里先不说,毕竟篇幅太长了。下一期会进行介绍。