按键对Lua表进行排序 [英] Sorting a Lua table by key

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

问题描述

我经历了许多问题和Google结果,但是找不到解决方案.

I have gone through many questions and Google results but couldn't find the solution.

我正在尝试使用Lua中的table.sort函数对表进行排序,但是我不知道如何使用它.

I am trying to sort a table using table.sort function in Lua but I can't figure out how to use it.

我有一个表,该表具有作为随机数值的键.我想按升序对它们进行排序.我也浏览了Lua Wiki页面,但是table.sort仅适用于表值.

I have a table that has keys as random numeric values. I want to sort them in ascending order. I have gone through the Lua wiki page also but table.sort only works with the table values.

t = { [223]="asd", [23]="fgh", [543]="hjk", [7]="qwe" }

我想要它:

t = { [7]="qwe", [23]="fgh", [223]="asd", [543]="hjk" }

推荐答案

您无法设置使用pairs从哈希(表的内容)中检索元素的顺序.您需要从该表中获取键,将键作为其自己的表排序,然后使用这些排序后的键从原始表中检索值:

You cannot set the order in which the elements are retrieved from the hash (which is what your table is) using pairs. You need to get the keys from that table, sort the keys as its own table, and then use those sorted keys to retrieve the values from your original table:

local t = { [223]="asd", [23]="fgh", [543]="hjk", [7]="qwe" }
local tkeys = {}
-- populate the table that holds the keys
for k in pairs(t) do table.insert(tkeys, k) end
-- sort the keys
table.sort(tkeys)
-- use the keys to retrieve the values in the sorted order
for _, k in ipairs(tkeys) do print(k, t[k]) end

这将打印

7   qwe
23  fgh
223 asd
543 hjk

另一种选择是提供您自己的迭代器,而不是pairs来按需要的顺序对表进行迭代,但是键的排序可能很简单,可以满足您的需求.

Another option would be to provide your own iterator instead of pairs to iterate the table in the order you need, but the sorting of the keys may be simple enough for your needs.

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

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