另一篇博客里写过lua按key遍历的迭代器

function pairsByKeys(t)--按key遍历
    local a = {}
    for n in pairs(t) do
        a[#a+1] = n
    end
    table.sort(a)
    local i = 0
    return function()
        i = i + 1
        return a[i], t[a[i]]
    end
end

比如:

local testTable = {[1] = 2,[3] = 4,[100] = 6, [80] = 7,[55] = 8}
for i,v in pairsByKeys(testTable) do
print(i.."="..v)

end

输出结果为:

1=2
3=4
55=8
80=7
100=6
[Finished in 0.0s]

由此可以延伸出另一种迭代器按table中某个值排序

function parisByAValue(key,t)--按某个值排序
    local a = {}
    for n in pairs(t) do
        if not a[t[n][key]] then
            a[t[n][key]] = {}
        end
        local temp = a[t[n][key]]
        temp[#temp+1] = n
    end
    local b = {}
    for k,v in pairsByKeys(a) do
        if type(v) == "table" then
            for key,value in pairs(v) do
                b[#b+1] = value
            end
        end
    end
    local i = 0
    return function()
        i = i+1
        return b[i],t[b[i]]
    end
end
比如:

local testTable = {{["exp"] = 200},{["exp"] = 5},{["exp"] = 8},{["exp"] = 1000},{["exp"] = 100}}

for i,v in parisByAValue("exp",testTable) do
print(i.."="..v.exp)
end

输出结果:

2=5 3=8 5=100 1=200 4=1000 [Finished in 0.0s]