使用Lua中的一个类对对象表进行排序。

我试图使用 Lua 中的一个名为 Name 的类来排序对象表。在 Python 中,您可以执行以下操作:

sorted_table = sorted(objects, key=lambda x: x.Name)

在 Lua 中,您可以使用以下优雅的方法吗?

到目前为止,我已经尝试过:

sorted_table = table.sort(objects, function(a,b) return a.name < b.name end))

但它给了我这个错误:

[string "table.sort(objects, function(a,b) re..."]:1: attempt to compare two nil values

当我转储表时,它看起来像这样:

table: 000000000AF9BE40
    1 = Polygon (0x00000000194A5250) [App: 'Fusion' on 127.0.0.1, UUID: f60e6d62-b100-42f3-b5d4-5799ccf86136]
    2 = Polygon (0x000000001956EC60) [App: 'Fusion' on 127.0.0.1, UUID: f60e6d62-b100-42f3-b5d4-5799ccf86136]
    3 = Polygon (0x000000001956FAF0) [App: 'Fusion' on 127.0.0.1, UUID: f60e6d62-b100-42f3-b5d4-5799ccf86136]
    4 = Polygon (0x0000000019570980) [App: 'Fusion' on 127.0.0.1, UUID: f60e6d62-b100-42f3-b5d4-5799ccf86136]
    5 = Polygon (0x00000000194A43C0) [App: 'Fusion' on 127.0.0.1, UUID: f60e6d62-b100-42f3-b5d4-5799ccf86136]

例如,如果我打印以下内容:

print(object[1].Name)
print(object[2].Name)

我会得到:

Name0001
Name0005

我想使用这些名称对我的表进行排序。

点赞
用户1198482
用户1198482

将表格复制到新的变量表中,然后对其进行排序。

参见此页面:http://lua-users.org/wiki/CopyTable

function shallowcopy(orig)
    local orig_type = type(orig)
    local copy
    if orig_type == 'table' then
        copy = {}
        for orig_key, orig_value in pairs(orig) do
            copy[orig_key] = orig_value
        end
    else --数值、字符串、布尔值等
        copy = orig
    end
    return copy
end

a={
    {name="Name0001"},
    {name="Name0004"},
    {name="Name0003"}
}
b=shallowcopy(a)
table.sort(b,function(aa,bb) return aa.name < bb.name end)

现在b已经有了排序后的值

2014-04-04 18:06:07
用户869951
用户869951

你使用了错误的字段名:

sorted_table = table.sort(objects, function(a,b) return a.Name < b.Name end)

此外,在你的帖子中,你有两个闭合的括号 )),肯定只是你帖子中的拼写错误,因为在排序执行之前,这将导致语法错误被标记出来。

2014-04-04 23:14:21