在for循环中,使用pairs()和ipairs()循环有什么区别?此页面同时使用:Lua文档
使用ipairs():
a = {"one", "two", "three"}
for i, v in ipairs(a) do
print(i, v)
end
Run Code Online (Sandbox Code Playgroud)
结果:
1 one
2 two
3 three
Run Code Online (Sandbox Code Playgroud)
使用pairs():
a = {"one", "two", "three"}
for i, v in pairs(a) do
print(i, v)
end
Run Code Online (Sandbox Code Playgroud)
结果:
1 one
2 two
3 three
Run Code Online (Sandbox Code Playgroud)
您可以在这里进行测试:Lua演示
Ala*_*got 23
pairs()并且ipairs()略有不同。
pairs()返回键值对,并且主要用于关联表。密钥顺序未指定。 ipairs()返回索引值对,并且主要用于数字表。数组中的非数字键将被忽略,而索引顺序是确定性的(按数字顺序)。下面的代码片段对此进行了说明。
> 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
>
Run Code Online (Sandbox Code Playgroud)
当您创建没有键的表时(如您的问题所示),它的行为就像一个数字数组,并且行为或成对和ipair是相同的。
a = {"one", "two", "three"}
Run Code Online (Sandbox Code Playgroud)
a[1]="one" a[2]="two" a[3]="three"
与pairs()和等效,并且ipairs()将是相同的(除非不能保证的顺序pairs())。
arrayLua 中没有-type,只有tables 可能具有从索引 1 开始的连续元素。
与数字 for 循环相比,通用 for 循环需要三个值:
它使用上下文值和索引值调用可调用函数,将所有返回值存储在提供的新变量中。第一个值另外保存为新的索引值。
现在循环可调用的一些代表性示例:
ipairs(t)返回一个函数、表t和起点0。
该函数在道德上等价于:
function ipairs_next(t, i)
i = i + 1
var v = t[i]
if v ~= nil then
return i, v
end
end
Run Code Online (Sandbox Code Playgroud)
因此,会显示从 1 开始直到第一个缺失的所有数字条目。
pairs(t)要么委托给t的元表,特别是委托给__pairs(t),要么返回函数next、表t和起点nil。
next接受一个表和一个索引,并返回下一个索引和关联值(如果存在)。
因此,所有元素都以某种任意顺序显示。
一个人对这个函数的创造性是没有限制的,这就是 vanilla Lua 所期望的。有关用户编写的可调用对象的示例,
请参阅“ Bizzare”尝试在 Lua 中调用表值” ,以及如果第一个值实际上不是可调用对象,某些方言会如何反应。