在Lua中按值对表进行关联排序 [英] Associatively sorting a table by value in Lua

查看:166
本文介绍了在Lua中按值对表进行关联排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个键=>值表,我想在Lua中排序.键都是整数,但不是连续的(有含义). Lua唯一的排序功能似乎是 table.sort ,它将表视为简单数组,丢弃原始键及其与特定项的关联.相反,我实质上是希望能够使用 PHP的asort() 函数

I have a key => value table I'd like to sort in Lua. The keys are all integers, but aren't consecutive (and have meaning). Lua's only sort function appears to be table.sort, which treats tables as simple arrays, discarding the original keys and their association with particular items. Instead, I'd essentially like to be able to use PHP's asort() function.

我所拥有的:

items = {
    [1004] = "foo",
    [1234] = "bar",
    [3188] = "baz",
    [7007] = "quux",
}

排序操作后我想要什么:

What I want after the sort operation:

items = {
    [1234] = "bar",
    [3188] = "baz",
    [1004] = "foo",
    [7007] = "quux",
}

有什么想法吗?

基于答案,我将假定这只是我正在使用的特定嵌入式Lua解释器的古怪之处,但在我所有的测试中,均pairs()始终按添加到表中的顺序返回表项. (即,上面的两个声明将以不同的方式进行迭代).

Based on answers, I'm going to assume that it's simply an odd quirk of the particular embedded Lua interpreter I'm working with, but in all of my tests, pairs() always returns table items in the order in which they were added to the table. (i.e. the two above declarations would iterate differently).

不幸的是,由于这不是正常行为,因此我似乎无法获得所需的东西. (当然)Lua没有内置必要的工具,而且嵌入式环境太有限,我无法解决.

Unfortunately, because that isn't normal behavior, it looks like I can't get what I need; Lua doesn't have the necessary tools built-in (of course) and the embedded environment is too limited for me to work around it.

还是,谢谢大家的帮助!

Still, thanks for your help, all!

推荐答案

您似乎误会了一些东西.您在这里拥有的是关联数组.关联数组没有明确的顺序,例如只有内部表示形式(通常是排序的)才能对它们进行排序.

You seem to misunderstand something. What you have here is a associative array. Associative arrays have no explicit order on them, e.g. it's only the internal representation (usually sorted) that orders them.

简而言之-在Lua中,您发布的两个数组都相同.

In short -- in Lua, both of the arrays you posted are the same.

您想要的是这样的表示形式:

What you would want instead, is such a representation:

items = {
    {1004, "foo"},
    {1234, "bar"},
    {3188, "baz"},
    {7007, "quux"},
}

虽然您现在无法按索引获取它们(它们被索引为1、2、3、4,但是您可以创建另一个索引数组),但是您可以使用table.sort对它们进行排序.

While you can't get them by index now (they are indexed 1, 2, 3, 4, but you can create another index array), you can sort them using table.sort.

排序函数将是:

function compare(a,b)
  return a[1] < b[1]
end

table.sort(items, compare)

这篇关于在Lua中按值对表进行关联排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆