用法
foo = {};
foo['a'] = 1;
foo['b'] = 2;
foo['c'] = 3;
bar = {};
bar[1] = 1;
bar[2] = 2;
bar[3] = 3;
-- 打印结果:nil:因为ipairs无法遍历索引不是数字或索引不是从数字1开始的table
for index,value in ipairs(foo) do
print(index,value);
end
--[[打印出
a 1
b 2
c 3
]]
for index,value in pairs(foo) do
print(index,value)
end
--[[以下两个for chunk的结果相同
对于索引为全数字且从1开始的table,ipairs和pairs完全相同
结果:
1 1
2 2
3 3
]]
for index,value in ipairs(bar) do
print(index,value);
end
for index,value in pairs(bar) do
print(index,value);
end

本文详细介绍了Lua中ipairs与pairs函数的使用方法及其区别。通过具体示例展示了两者在遍历table时的不同行为,包括对数字索引及非连续索引table的处理方式。
2742

被折叠的 条评论
为什么被折叠?



