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
784 views
in Technique[技术] by (71.8m points)

for loop - What is the difference of pairs() vs. ipairs() in Lua?

In a for loop, what is the difference between looping with pairs() and ipairs()? This page uses both: Lua Docs

With ipairs():

a = {"one", "two", "three"}
for i, v in ipairs(a) do
  print(i, v)
end

Result:

1   one
2   two
3   three

With pairs():

a = {"one", "two", "three"}
for i, v in pairs(a) do
  print(i, v)
end

Result:

1   one
2   two
3   three

You can test it here: Lua Demo

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

pairs() and ipairs() are slightly different.

  • pairs() returns key-value pairs and is mostly used for associative tables. key order is unspecified.
  • ipairs() returns index-value pairs and is mostly used for numeric tables. Non numeric keys in an array are ignored, while the index order is deterministic (in numeric order).

This is illustrated by the following code fragment.

> u={}
> u[1]="a"
> u[3]="b"
> u[2]="c"
> u[4]="d"
> u["hello"]="world"
> for key,value in ipairs(u) do print(key,value) end
1   a
2   c
3   b
4   d
> for key,value in pairs(u) do print(key,value) end
1   a
hello   world
3   b
2   c
4   d
> 

When you create an tables without keys (as in your question), it behaves as a numeric array and behaviour or pairs and ipairs is identical.

a = {"one", "two", "three"}

is equivalent to a[1]="one" a[2]="two" a[3]="three" and pairs() and ipairs() will be identical (except for the ordering that is not guaranteed in pairs()).


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

...