DAY 13
0
Software Development

# 進步的for迴圈

``````for i = 1, 10, 1 do
print(i)
end
``````

``````#include <stdio.h>

int main(void){
int i = 0;
for(i = 1; i <= 10; i++){
printf("%d\n", i);
}
}
``````

``````for i = 10, 1, -1 do
print(i)
end
``````

`for-do`也是一個區塊，於一開始宣告的變數僅`do-end`內部可見。這表示下方寫法中，進步條件指的是外部的`i`，其值為`1`。結果與輸出1-10相同。

``````i = 1
for i = 1, 10, i do
print(i)
end
``````

# pairs & ipairs初探 - for-in迴圈

`for-in`迴圈用於迭代陣列(`array`)或表格(`table`)時。

Lua是沒有array型態的(還記得8種基礎型別嗎)，關於這點之後會在說明。

## 迭代陣列

``````array = {"one", "two", "three"}

for i, v in ipairs(array) do
print(i, v)
end
``````

1 one
2 two
3 three

※ 注意！ `ipairs``pairs`，以及陣列長度`#array`等還有一些未提到的事情在。

``````arr = ["one", "two", "three"]

for i, v in enumerate(arr):
print(i,v)
``````

``````array = {"one", "two", "three"}

for i in ipairs(array) do
print(i, array[i])
end
``````

``````array = {"one", "two", "three"}

for _,v in ipairs(array) do
print(_,v)
end
``````

(Golang有明確的規範)

## 迭代表格

``````tb = {
["key1"] = "one",
["key2"] = "two",
["key3"] = "three",
}

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

key3 three
key1 one
key2 two

※ Note: 也可以用上面同樣方式忽略`v``k`

30天 Lua重拾筆記36