如何在Lua中遍历表? [英] How to iterate through table in Lua?
问题描述
所以,我有一张桌子沿这几行:
So, I have a table something along these lines:
arr =
{
apples = { 'a', "red", 5 },
oranges = { 'o', "orange", 12 },
pears = { 'p', "green", 7 }
}
似乎无法根据它们的索引来访问它们,并且值本身是表,所以我只是将嵌套表的第一个值作为它的索引,所以现在看起来像这样:
It doesn't seem like it's possible to access them based on their index, and the values themselves are tables, so I just made the first value of the nested table the index of it, so it now looks like this:
arr =
{
apples = { 0, 'a', "red", 5 },
oranges = { 1, 'o', "orange", 12 },
pears = { 2, 'p', "green", 7 }
}
因此,现在无论何时我使用这些表之一,我都知道索引是什么,但仍然无法使用索引访问该表,因此我开始编写一个遍历所有表的函数,并进行检查索引,直到找到正确的索引为止.然后我意识到...如果无法通过它们的索引引用它们,该如何遍历它们?所以,现在我被卡住了.我真的很希望大多数时候都可以输入arr.apples vs arr [1],但是当然有必要同时输入两者.
So, now any time I use one of these tables, I know what the index is, but still can't get to the table using the index, so I started to write a function that loops through them all, and check the indexes until it finds the right one. Then I realized... how can I loop through them if I can't already refer to them by their index? So, now I'm stuck. I really want to be able to type arr.apples vs arr[1] most of the time, but of course it's necessary to do both at times.
推荐答案
要遍历表中的所有键-值对,可以使用pairs
:
To iterate over all the key-value pairs in a table you can use pairs
:
for k, v in pairs(arr) do
print(k, v[1], v[2], v[3])
end
输出:
pears 2 p green
apples 0 a red
oranges 1 o orange
编辑:请注意,Lua不保证表关联部分的任何迭代顺序.如果要按特定顺序访问项目,请从arr
检索密钥并对其进行排序.然后通过排序的键访问arr
:
Edit: Note that Lua doesn't guarantee any iteration order for the associative part of the table. If you want to access the items in a specific order, retrieve the keys from arr
and sort it. Then access arr
through the sorted keys:
local ordered_keys = {}
for k in pairs(arr) do
table.insert(ordered_keys, k)
end
table.sort(ordered_keys)
for i = 1, #ordered_keys do
local k, v = ordered_keys[i], arr[ ordered_keys[i] ]
print(k, v[1], v[2], v[3])
end
输出:
apples a red 5
oranges o orange 12
pears p green 7
这篇关于如何在Lua中遍历表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!