lua:遍历表中的所有对 [英] lua: iterate through all pairs in table

查看:266
本文介绍了lua:遍历表中的所有对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个稀疏的lua表,需要对其进行迭代.问题是,似乎lua从1开始迭代,并在找到nil值后立即终止.这是示例:

I have a sparse lua table and I need to iterate over it. The Problem is, it seems that lua begins the iteration at 1, and terminates as soon as it finds a nil value. Here's and example:

> tab={}
> tab[2]='b'
> tab[5]='e'
> for i,v in ipairs(tab) do print(i,v) end
>               --nothing is output here
> tab[1]='a'
> for i,v in ipairs(tab) do print(i,v) end
1   a
2   b
>               --terminates after 2 (first nil value is tab[3])

有什么方法可以得到想要的输出:

Is there any way to get the desired output:

1   a
2   b
5   e

推荐答案

您必须使用pairs而不是ipairs.

tab={}

tab[1]='a'
tab[2]='b'
tab[5]='e'

for k, v in pairs(tab) do print(k, v) end

将输出(以任何顺序):

Will output (in any order):

1   a
2   b
5   e

ipairs迭代从1开始到第一对nil对中断的连续整数键.

ipairs iterates over sequential integer keys, starting at 1 and breaking on the first nil pair.

pairs遍历表中的所有键-值对.请注意,不能保证以特定顺序进行迭代.

pairs iterates over all key-value pairs in the table. Note that this is not guaranteed to iterate in a specific order.

这篇关于lua:遍历表中的所有对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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