例子1:
a = {[1]="a","b","c","d","e","f" } for k,v in ipairs(a) do print(k) print(v.."\n") end
输出1:
>lua -e "io.stdout:setvbuf 'no'" "luatest.lua"
1
b
2
c
3
d
4
e
5
f
>Exit code: 0
---------------------------------------------------------------------------------------------------------------------
例子2:
a = {"a","b","c","d","e","f" } for k,v in ipairs(a) do print(k) print(v.."\n") end
输出2:
>lua -e "io.stdout:setvbuf 'no'" "luatest.lua"
1
a
2
b
3
c
4
d
5
e
6
f
>Exit code: 0
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
例子3:
a = {[1]="a",[2]="b",[3]="c",[4]="d",[5]="e",[6]="f"} for k,v in ipairs(a) do print(k) print(v.."\n") end
输出3:
>lua -e "io.stdout:setvbuf 'no'" "luatest.lua"
1
a
2
b
3
c
4
d
5
e
6
f
>Exit code: 0
总结:
pairs会遍历所有元素,ipairs不遍历设置索引值的元素(如果设置的索引值是连着默认值时可以遍历,例如例子1中设置[6]="a",那么可以遍历它,也就是说遍历连续的索引值)