【问题标题】:Lua - Sorting a table alphabeticallyLua - 按字母顺序对表格进行排序
【发布时间】:2009-07-18 04:07:50
【问题描述】:

我有一个表格,里面填满了用户输入的随机内容。我希望我的用户能够快速搜索此表,促进搜索的一种方法是按字母顺序对表进行排序。最初,表格看起来像这样:

myTable = {
    Zebra = "black and white",
    Apple = "I love them!",
    Coin = "25cents"
}

我能够实现pairByKeys() 函数,它允许我按字母顺序输出表格内容,但不能以这种方式存储它们。由于搜索的设置方式,表格本身需要按字母顺序排列。

function pairsByKeys (t, f)
    local a = {}
    for n in pairs(t) do
        table.insert(a, n)
    end
    table.sort(a, f)
    local i = 0      -- iterator variable
    local iter = function ()   -- iterator function
        i = i + 1
        if a[i] == nil then
            return nil
        else
            return a[i], t[a[i]]
        end
    end
    return iter
end

一段时间后,我开始理解(可能是错误的 - 你告诉我)非数字索引表不能按字母顺序排序。于是我开始想办法解决这个问题——我想到的一种方法是对表格进行排序,然后将每个值放入一个数字索引数组中,如下所示:

myTable = {
    [1] = { Apple = "I love them!" },
    [2] = { Coin = "25cents" },
    [3] = { Zebra = "black and white" },
}

原则上,我觉得这应该可行,但由于某种原因,我遇到了困难。我的表似乎没有排序。这是我使用上述函数对表格进行排序的函数:

SortFunc = function ()
    local newtbl = {}
    local t = {}
    for title,value in pairsByKeys(myTable) do
        newtbl[title] = value
        tinsert(t,newtbl[title])
    end
    myTable = t
end

myTable 仍然没有最终被排序。为什么?

【问题讨论】:

    标签: sorting lua


    【解决方案1】:

    Lua 的 table 可以是混合的。对于从 1 开始的数字键,它使用 vector,而对于其他键,它使用 hash

    例如,{1="foo", 2="bar", 4="hey", my="name"}
    1 & 2,将被放置在一个向量中,4 & my 将被放置在一个哈希表中。 4 破坏了序列,这就是将其包含到哈希表中的原因。

    有关如何对 Lua 表进行排序的信息,请查看此处:19.3 - Sort

    【讨论】:

      【解决方案2】:

      您的新表需要连续的整数键,并且需要值本身作为表。所以你想要这个订单上的东西:

      SortFunc = function (myTable)
          local t = {}
          for title,value in pairsByKeys(myTable) do
              table.insert(t, { title = title, value = value })
          end
          myTable = t
          return myTable
      end
      

      这假设 pairsByKeys 做了我认为它做的事情......

      【讨论】:

      • 这个解决方案对我有用。我试图另存为 = <value> (这不起作用),而您的通过保存为“title” = <title> 和“value” = <value> 来实现相同的效果。谢谢!</value>
      猜你喜欢
      • 2019-05-14
      • 1970-01-01
      • 2019-06-25
      • 2011-08-29
      • 1970-01-01
      • 2013-05-02
      • 2014-02-08
      • 2017-05-22
      • 1970-01-01
      相关资源
      最近更新 更多