DAY 20
0
Software Development

# 建立陣列

``````programming_language = {
"C",
"C#",
"C++",
"Java",
"Swift",
"Python",
}
``````

# 陣列取值

``````print(programming_language[1]) -- => Output: "C"
``````

# 陣列長度

``````print(#programming_language) -- => Output: 7
``````

# 迭代陣列

## 一般for迴圈方法

``````for i=1, #programming_language, 1 do
print(i, #programming_language[i], programming_language[i])
end
``````

## for-in + ipairs() 方法

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

``````for i, lang in ipairs(programming_language) do
print(i, #lang, lang)
end
``````

# 增加陣列長度

``````print(#programming_language) --> Output: 7
programming_language[#programming_language + 1] = 'ECMAScript'
print(#programming_language) --> Output: 8
``````

``````print(#programming_language) --> Output: 8
table.insert(programming_language, "Shell Script")
print(#programming_language) --> Output: 9
``````

# 刪除陣列

``````print(#programming_language) --> Output: 9
programming_language[#programming_language] = nil
print(#programming_language) --> Output: 8
``````

!!強烈建議只總是刪除尾端元素!!

``````print(#programming_language) --> Output: 8
programming_language[2] = nil -- delete "C#"
print(#programming_language) --> Output: 8  ---- What's!?
``````

## ipairs()迭代不正常了？

``````for i, lang in ipairs(programming_language) do
print(i, #lang, lang)
end
``````

1 1 C
-- 其他值呢？

ipairs()的寫法可能不能用了，只能使用一般`for`迴圈寫法：

``````for i=1, #programming_language, 1 do
print(i, programming_language[i])
end
``````

1 C
2 nil
3 C++
4 Java
5 Swift
6 Python
8 ECMAScript

# 作業

``````arr = {
[1] = 1,
[2] = 1,
[3] = 1,
[4] = 1,
[5] = 1,
}

print(#arr) --> 5
``````

## 作業

``````arr = {
[0] = 1,
[1] = 1,
[2] = 1,
[3] = 1,
[4] = 1,
[5] = 1,
}

print(#arr) --> ?
``````

1. 5

# 其他應該注意事項

## 總是使用正常的陣列初始化

``````arr1 = {1,nil,3,4,5}
arr2 = {1,2,nil,4,5}

print(#arr1) --> 5
print(#arr2) --> 5
``````

``````arr1 = {
[1] = 1,
[2] = nil,
[3] = 3,
[4] = 4,
[5] = 5
}

arr2 = {
[1] = 1,
[2] = 2,
[3] = nil,
[4] = 4,
[5] = 5
}

print(#arr1) --> 1
print(#arr2) --> 5
``````

## 總是只在尾端插入元素

``````arr = {1,nil,3,4,5}

print(#arr) --> 5

arr[7] = 7
print(#arr) --> 7 -- What's !? 直接變成7

arr[9] = 9
print(#arr) --> 7 -- What's !? 長度沒有增加
``````

OS: 執行結果不一樣？別問我，我也不知道為什麼

30天 Lua重拾筆記36