lua ipairs(t) and pairs(t)
lua ipairs(t) and pairs(t)
andrew810810 发表于1年前
lua ipairs(t) and pairs(t)
• 发表于 1年前
• 阅读 2
• 收藏 0
• 评论 0

# ipairs(t) and pairs(t)

reference:

http://www.lua.org/manual/5.3/manual.html

### `ipairs (t)`

Returns three values (an iterator function, the table `t`, and 0) so that the construction

`for i,v in ipairs(t) do body end`

will iterate over the key–value pairs (`1,t[1]`), (`2,t[2]`), ..., up to the first nil value.

### `pairs (t)`

If `t` has a metamethod `__pairs`, calls it with `t` as argument and returns the first three results from the call.

Otherwise, returns three values: the `next` function, the table `t`, and nil, so that the construction

`for k,v in pairs(t) do body end`

will iterate over all key–value pairs of table `t`.

See function `next` for the caveats of modifying the table during its traversal.

## 示例1：

``````local tabFiles = {
[2] = "test2",
[4] = "test3",
[3] = "test1"
}

for k, v in ipairs(tabFiles) do
print(k, v)
end
``````

## 示例2：

``````local tabFiles = {
[2] = "test2",
[4] = "test3",
[3] = "test1"
}

for k, v in pairs(tabFiles) do
print(k, v)
end
``````

``````3	test1
2	test2
4	test3
``````

## 示例3：

``````local tabFiles1 = {
[3] = "test2",
[6] = "test3",
[4] = "test1"
}

for k, v in pairs(tabFiles1) do
print(k, v)
end
``````

``````3	test2
6	test3
4	test1``````

## 示例4：

``````local tabFiles2 = {
[1] = "test2",
[6] = "test3",
[4] = "test1"
}
for k, v in ipairs(tabFiles2) do
print(k, v)
end
``````

``1	test2``

## 示例5：

``````local tabFiles2 = {
[1] = "test2",
[6] = "test3",
[4] = "test1"
}
for k, v in pairs(tabFiles2) do
print(k, v)
end``````

``````1	test2
6	test3
4	test1``````

## 示例6：

``````local tabFiles3 = {
[2] = "test2",
[6] = "test3",
[1] = "test1",
"ok",
}
for k, v in ipairs(tabFiles3) do
print(k, v)
end``````

``````1	ok
2	test2``````

## 示例7：

``````local tabFiles3 = {
[2] = "test2",
[6] = "test3",
[1] = "test1",
"ok",
}
for k, v in pairs(tabFiles3) do
print(k, v)
end``````
``````1	ok
2	test2
6	test3``````

table中定义了key为1的value，以及没有定义key的value，发现对于key为1的value会被没有定义key的value覆盖。

×