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:
我有一个稀疏的lua表,我需要对它进行迭代。问题是,lua似乎在1开始迭代,一旦发现一个空值就终止。这里的例子:
> 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
1 个解决方案
#1
26
You must use pairs
instead of ipairs
.
你必须用对而不是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
iterates over sequential integer keys, starting at 1 and breaking on the first nil
pair.
ipairs迭代顺序整数键,从1开始,在第一个nil对上中断。
pairs
iterates over all key-value pairs in the table. Note that this is not guaranteed to iterate in a specific order.
对遍历表中的所有键-值对。注意,这不能保证以特定的顺序迭代。
#1
26
You must use pairs
instead of ipairs
.
你必须用对而不是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
iterates over sequential integer keys, starting at 1 and breaking on the first nil
pair.
ipairs迭代顺序整数键,从1开始,在第一个nil对上中断。
pairs
iterates over all key-value pairs in the table. Note that this is not guaranteed to iterate in a specific order.
对遍历表中的所有键-值对。注意,这不能保证以特定的顺序迭代。