在lua中table标准库提供一个排序函数,接受一个表作为输入参数并且排序表中的元素。这个函数必须能够对不同类型的值按升序或者降序排序。lua不是尽可能多地提供参数来满足这些情况的需要,而是接受一个排序函数作为参数。
例如:
network = {
{name = "grauna" , IP = "210.26.30.34"},
{name = "arraial", IP = "210.26.30.23"},
{name = "lua",IP = "210.26.23.12"},
{name = "derain",IP = "210.26.23.20"},
}
for i,v in ipairs(network) do
print(v.name)
print(v.IP)
end
print("after sort table:\n")
table.sort(network,function(a,b) return (a.name>b.name) end)
for i,v in ipairs(network) do
print(v.name)
print(v.IP)
end
输出为:
grauna
210.26.30.34
arraial
210.26.30.23
lua
210.26.23.12
derain
210.26.23.20
after sort table:
lua
210.26.23.12
grauna
210.26.30.34
derain
210.26.23.20
arraial
210.26.30.23