如何遍历表格并保持顺序? [英] How to loop through the table and keep the order?
问题描述
我设置了以下表格:
local a = {
[12 * 30 * 24 * 60 * 60] = 'year',
[30 * 24 * 60 * 60] = 'month',
[24 * 60 * 60] = 'day',
[60 * 60] = 'hour',
[60] = 'minute',
[1] = 'second'
}
但是,当我配对循环并打印键时,值得到了:
However, when I pair loop over it and print key, value I get this:
for seconds, str in pairs(a) do
print (seconds, str)
end
----------
31104000 year
60 minute
3600 hour
1 second
2592000 month
86400 day
如您所见,订单被完全弄乱了. 如何遍历表格并保持订单顺序?
As you can see, the order is completely messed up. How can I loop over the table and keep the order?
推荐答案
您正在误解中进行工作:
Lua表显式地不保留元素输入的顺序,因此在事实之后就无法引用该顺序.
(实际上,它们目前是数组和哈希图的混合体)
You are laboring under a misconception:
Lua tables explicitly do not preserve the order in which elements were entered, so there is no way to refer to that order after the fact.
(under the hood, they are currently a hybrid of an array and a hash-map)
您可能真正想要的(在提供的示例之后)是迭代键所排序的元素.
当然可以,但是需要一个自定义的迭代器.
What you probably actually want (going after your provided example), is iterating the elements ordered by the key.
That is certainly possible, but requires a custom iteratorator.
迭代器的工作方式:
lua __pairs的实际实现是什么?
Lua中有状态迭代器与无状态迭代器之间的区别
How iterators work:
what is actual implementation of lua __pairs?
Difference between stateful and stateless iterators in Lua
function sorted_iter(t)
local i = {}
for k in next, t do
table.insert(i, k)
end
table.sort(i)
return function()
local k = table.remove(i)
if k ~= nil then
return k, t[k]
end
end
end
因此,您的循环变为:
for seconds, str in sorted_iter(a) do
print (seconds, str)
end
这篇关于如何遍历表格并保持顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!