对包含表的表进行排序

时间:2013-10-03 19:22:02

标签: sorting lua lua-table

我可以使用以下代码对包含两条信息(名称和第二部分,例如年龄)的表进行排序:

t = {
Steve = 4,
Derek = 1,
Mike = 5,
Steph = 10,
Mary = 7,
Danny = 2
}

function pairsByKeys (t,f)  
    local a = {}

    for x in pairs (t) do
        a[#a + 1] = x
    end

    table.sort(a,f)
    local i = 0
    return function ()
    i = i + 1
    return a[i], t[a[i]]
    end
end

for a,t in pairsByKeys (t) do
    print (a,t)
end

结果:

Danny   2
Derek   1
Mary    7
Mike    5
Steph   10
Steve   4

我有一个场景,按照惯例,每个人的姓名标签都包含一个条形码。扫描时,该条形码将关于每个人的四条信息输入到表格数据库中。该数据库由以下部分组成:

t = {
    {name = "Mike", addr = "738 Rose Rd", age = 30, phone = "333-902-6543"}
    {name = "Steph", addr = "1010 Mustang Dr", age = 28, phone = "555-842-0606"}
    {name = "George", addr = "211 Glass St", age = 34, phone = "111-294-9903"}
}

但是如何更改我的代码以按年龄对所有四个条目(姓名,地址,年龄,电话)进行排序并保持所有变量彼此一致?

我一直在尝试进行实验,并且正忙着按pairs对表进行排序,并更好地了解如何执行table.sort。但现在我想采取另一个步骤。

我可以从这里的一位编程大师那里得到一些帮助吗?!非常感谢大家!谢谢!

1 个答案:

答案 0 :(得分:2)

您可以将年龄作为表格的关键字:

t = {
    [30] = {name = "Mike", addr = "738 Rose Rd", age = 30, phone = "333-902-6543"},
    [28] = {name = "Steph", addr = "1010 Mustang Dr", age = 28, phone = "555-842-0606"},
    [34] = {name = "George", addr = "211 Glass St", age = 34, phone = "111-294-9903"},
}

function pairsByKeys (t,f)
    local a = {}

    for x in pairs (t) do
        a[#a + 1] = x
    end

    table.sort(a,f)
    local i = 0
    return function ()
        i = i + 1
        return a[i], t[a[i]]
    end
end


for a,t in pairsByKeys (t) do
    print (t.name, t.addr, t.age, t.phone)
end

修改

否则,如果您不想更改t的结构,可以更改迭代器生成函数以跟踪索引:

t = {
    {name = "Mike", addr = "738 Rose Rd", age = 30, phone = "333-902-6543"},
    {name = "Steph", addr = "1010 Mustang Dr", age = 28, phone = "555-842-0606"},
    {name = "George", addr = "211 Glass St", age = 34, phone = "111-294-9903"},
}

function pairsByAgeField(t,f)
    local a = {}
    local index = {}

    for _, x in pairs(t) do
        local age = x.age
        a[#a + 1] = age
        index[age] = x
    end

    table.sort(a,f)
    local i = 0
    return function ()
        i = i + 1
        return a[i], index[a[i]]
    end
end


for a,t in pairsByAgeField(t) do
    print (t.name, t.addr, t.age, t.phone)
end

当然,这使得pairsByAgeField不太适用于原始pairsByKeys(它假定正在迭代的表具有给定的结构),但如果您经常需要处理,这不是问题您的应用程序中的t等表格。