Lua 对表格中的表格值进行排序

我对 Lua 很陌生,请多关照。

我希望基于"error"键排序结果。对于这个例子,输出应该是:

c  50   70
d  25   50
b  30   40
a  10   20

这是我的脚本:

records = {}

records["a"] = {["count"] = 10, ["error"] = 20}
records["b"] = {["count"] = 30, ["error"] = 40}
records["c"] = {["count"] = 50, ["error"] = 70}
records["d"] = {["count"] = 25, ["error"] = 50}

function spairs(t, order)
    -- collect the keys
    local keys = {}
    for k in pairs(t) do keys[#keys+1] = k end

    -- if order function given, sort by it by passing the table and keys a, b,
    -- otherwise just sort the keys
    if order then
        table.sort(keys, function(a,b) return order(t, a, b) end)
    else
        table.sort(keys)
    end

    -- return the iterator function
    local i = 0
    return function()
        i = i + 1
        if keys[i] then
            return keys[i], t[keys[i]]
        end
    end
end

for k, v in pairs(records) do
    for m, n in pairs(v) do
        for x, y in spairs(v, function(t,a,b) return t[b] < t[a] end) do
            line = string.format("%s %5s   %-10d", k, n, y)
        end
    end
    print(line)

end

我在 这里关于排序的 StackOverflow 文章 中发现了一些东西并尝试进行实现。但它不起作用,结果没有排序。

点赞
用户1190388
用户1190388

table.sort 仅在表元素被整数索引时起作用。根据您的情况;当您尝试调用 spairs 时,实际上您正在调用 counterror 索引上的 table.sort

首先,删除丑陋且与题意无关的嵌套 for..pairs 循环。您只需要 spairs 来完成您的任务。

for x, y in spairs(records, function(t, a, b) return t[b].error < t[a].error end) do
    print( x, y.count, y.error)
end

就这样。

2014-11-17 20:47:19