pairs与ipairs区别
pairs是无序遍历,ipairs是有序遍历
pairs支持key,value格式,ipairs 只支持key为数字
local a={a="a","b","c","d","e"}
for k,v in pairs(a) do
print(v)
end
print("-----------------------")
for k,v in ipairs(a) do
print(v)
end
输出
b
c
d
e
a
-----------------------
b
c
d
e
pairs可以遍历value为空的表,ipairs不可能遍历value为空的表,遇nil则退出遍历
local b={nil,"a","b","c"}
for k,v in pairs(b) do
print(v)
end
print("------------------------")
for k,v in ipairs(b) do
print(v)
end
local c={"a",nil,"b","c","d"}
for k,v in pairs(c) do
print(v)
end
print("-----------------------")
for k,v in ipairs(c) do
print(v)
end
输出
a
b
c
------------------------
a
b
c
d
-----------------------
a