Lua中的pairs()和ipairs()有什么区别? [英] What is the difference of pairs() vs. ipairs() in Lua?

查看:612
本文介绍了Lua中的pairs()和ipairs()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在for循环中,使用pairs()和ipairs()进行循环之间有什么区别?此页面同时使用: Lua Docs

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

使用ipairs():

With ipairs():

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

结果:

1   one
2   two
3   three

使用pairs():

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

结果:

1   one
2   two
3   three

您可以在此处进行测试: Lua演示

You can test it here: Lua Demo

推荐答案

pairs()ipairs()略有不同.

  • pairs()返回键值对,并且主要用于关联表.密钥顺序未指定.
  • ipairs()返回索引值对,并且主要用于数字表.数组中的非数字键将被忽略,而索引顺序是确定性的(按数字顺序).
  • 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
> 

创建没有键的表(如您的问题)时,它的行为就像一个数字数组,行为或成对和ipair是相同的.

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"}

等效于a[1]="one" a[2]="two" a[3]="three"pairs()ipairs()将是相同的(除了pairs()中不能保证的顺序).

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()).

这篇关于Lua中的pairs()和ipairs()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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