Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sorting Lua-按字母顺序对表进行排序_Sorting_Lua - Fatal编程技术网

Sorting Lua-按字母顺序对表进行排序

Sorting Lua-按字母顺序对表进行排序,sorting,lua,Sorting,Lua,我有一个表格,里面充满了用户输入的随机内容。我希望我的用户能够快速搜索这个表,一种方便他们搜索的方法是按字母顺序对表进行排序。最初,桌子看起来像这样: myTable = { Zebra = "black and white", Apple = "I love them!", Coin = "25cents" } 我能够实现pairsByKeys()函数,该函数允许我按字母顺序输出表中的内容,但不能以这种方式存储它们。由于搜索的设置方式,表本身需要按字母顺序排列 fun

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

myTable = {
    Zebra = "black and white",
    Apple = "I love them!",
    Coin = "25cents"
}
我能够实现pairsByKeys()函数,该函数允许我按字母顺序输出表中的内容,但不能以这种方式存储它们。由于搜索的设置方式,表本身需要按字母顺序排列

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仍然没有被排序。为什么?

Lua的桌子可以是混合的。对于数字键,从1开始,它使用向量,对于其他键,它使用散列。

例如,
{1=“foo”,2=“bar”,4=“hey”,my=“name”}

1和2将被放置在向量中,4和my将被放置在哈希表中4破坏了序列,这就是将其包含到哈希表中的原因


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

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

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
做了我认为它能做的事…

这个解决方案适合我。我试图另存为=(不起作用),而你的则通过另存为“title”和“value”来实现相同的效果。谢谢