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

查看:31
本文介绍了在 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.

还是谢谢大家的帮助!

推荐答案

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

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天全站免登陆