如何遍历Lua中的表? [英] How to iterate through table in Lua?

查看:33
本文介绍了如何遍历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 与 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屋!

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