Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

loops - lua: iterate through all pairs in table

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You must use pairs instead of 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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...