实例:(原理就是LUA集成的冒泡算法)
--排序的算法
function comps(a,b)
return a.id < b.id
end
--应用
table.sort(table_name,comps);
table_name 已经被修改
一、数值数组排序(字符串跟数值混在一起的数组是不能sort的)
- local test_table = {2,1,3}
- table.sort(test_table)
- for key,value in pairs(test_table) do
- print(key,value)
- end
输出结果:
- >lua -e "io.stdout:setvbuf 'no'" "test.lua"
- 1 1
- 2 2
- 3 3
- local test_table = {"a","c","b"}
- table.sort(test_table)
- for key,value in pairs(test_table) do
- print(key,value)
- end
- >lua -e "io.stdout:setvbuf 'no'" "test.lua"
- 1 a
- 2 b
- 3 c
- local test_table = {a=3,b=2,c=4,d=1}
- local key_table = {}
- --取出所有的键
- for key,_ in pairs(test_table) do
- table.insert(key_table,key)
- end
- --对所有键进行排序
- table.sort(key_table)
- for _,key in pairs(key_table) do
- print(key,test_table[key])
- end
- >lua -e "io.stdout:setvbuf 'no'" "test.lua"
- a 3
- b 2
- c 4
- d 1
function comps(a,b)
--先按id从大到小排序 如果id一样数量从大到小排序if( a.id > b.id) then
return true
elseif(a.id == b.id) then
return a.count>b.count
else
return false
end
end
local item={{id=70500,count=20},{id=70503,count=5},{id=70500,count=21},{id=70009,count=4},{id=70504,count=5}}
table.sort(item,comps)
for i=1,#item do
print(item[i].id .. " " .. item[i].count)
end