# for 控制结构

Lua 提供了一组传统的、小巧的控制结构，包括用于条件判断的 if 用于迭代的 while、repeat 和 for，本章节主要介绍 for 的使用。

#### for 数字型

for 语句有两种形式：数字 for（numeric for）和范型 for（generic for）。

for var = begin, finish, step do
--body
end

for i = 1, 5 do
print(i)
end

-- output:
1
2
3
4
5

...

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

-- output:
1
3
5
7
9

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

-- output:
...

for i = 1, math.huge do
if (0.3*i^3 - 20*i^2 - 500 >=0) then
print(i)
break
end
end

#### for 泛型

-- 打印数组a的所有值
local a = {"a", "b", "c", "d"}
for i, v in ipairs(a) do
print("index:", i, " value:", v)
end

-- output:
index:  1  value: a
index:  2  value: b
index:  3  value: c
index:  4  value: d

Lua 的基础库提供了 ipairs，这是一个用于遍历数组的迭代器函数。在每次循环中，i 会被赋予一个索引值，同时 v 被赋予一个对应于该索引的数组元素值。

-- 打印table t中所有的key
for k in pairs(t) do
print(k)
end

local days = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
}

  local revDays = {
["Sunday"] = 1,
["Monday"] = 2,
["Tuesday"] = 3,
["Wednesday"] = 4,
["Thursday"] = 5,
["Friday"] = 6,
["Saturday"] = 7
}

local x = "Tuesday"
print(revDays[x])  -->3

local days = {
"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday","Sunday"
}

local revDays = {}
for k, v in pairs(days) do
revDays[v] = k
end

-- print value
for k,v in pairs(revDays) do
print("k:", k, " v:", v)
end

-- output:
k:  Tuesday   v: 2
k:  Monday    v: 1
k:  Sunday    v: 7
k:  Thursday  v: 4
k:  Friday    v: 5
k:  Wednesday v: 3
k:  Saturday  v: 6