• 如果然后，否则
• 虽然做并重复，直到
• 数字对于
• 打破
• 转到

## 如果然后，否则

if 语句根据一个或多个条件选择要执行的语句块。有三种形式：

### 如果然后形成

``````if expression then
statements to execute if expression is not false or nil
end
<!--NeedCopy-->
``````

### 如果然后，形式

``````if expression then
statements to execute if expression is not false or nil
else
statements to execute if expression is false or nil
end
<!--NeedCopy-->
``````

### 如果然后别的表格

``````if expression1 then
statements to execute if expression1 is not false or nil
elseif expression2 then
statements to execute if expression2 is not false or nil
. . .
else
statements to execute if all expressions are false or nil
end
<!--NeedCopy-->
``````

``````if headers[name] then

local next_value_index = #(headers[name]) + 1

else

headers[name] = {name .. ":" .. value}

end
<!--NeedCopy-->
``````

• 表达式不像 C 和 Java 中的情况那样括在括号中。
• 没有等效于 C/Java 开关语句。您必须使用一系列 if seif 语句来执行等价操作。

## 虽然做并重复，直到

while 语句和 重复 语句提供由表达式控制的循环。

``````while expression do
statements to execute while expression is not false or nil
end

repeat

statements to execute until expression is not false or nil

until expression
<!--NeedCopy-->
``````

``````local a = {1, 2, 3, 4}
local sum, i = 0, 1 -- multiple assignment initializing sum and i
while i <= #a do -- check if at the end of the array
sum = sum + a[i] -- add array element with index i to sum
i = i + 1 -- move to the next element
end
<!--NeedCopy-->
``````

``````sum, i = 0, 1 -- multiple assignment initializing sum and i
repeat
sum = sum + a[i] -- add array element with index i to sum
i = i + 1 -- move to the next element
until i > #a -- check if past the end of the array
<!--NeedCopy-->
``````

`Cpu limit reached. Terminating extension execution in [[string "function extension function..."]]: line line-number.`

## 数字对于

``````for variable = initial, final, increment do

statements in the loop body

end
<!--NeedCopy-->
``````

``````sum = 0
for i = 1, #a do -- increment defaults to 1
sum = sum + a[i]
end
<!--NeedCopy-->
``````

for 循环的第二种类型是通用的，它可以用于更灵活的循环类型。它涉及函数的使用，所以将在函数引入后讨论。

## 打破

break 语句在一段时间内使用，重复或 for 循环。它将终止循环并在循环后的第一个语句中恢复执行。示例（也等同于前面的 while、重复和 for 循环）：

``````sum, i = 0, 1
while true do
if i > #a then
break
end
sum = sum + a[i]
i = i + 1
end
<!--NeedCopy-->
``````

## 转到

goto 语句可用于向前或向后跳转到标签。标签是一个标识符，其语法是:: label::。goto 语句是 goto 标签。示例（再次等同于前面的循环）：

``````sum, i = 0, 1
::start_loop::
if i > #a then
goto end_loop -- forward jump
end
sum = sum + a[i]
i = i + 1
goto start_loop -- backwards jump
::end_loop::
. . .
<!--NeedCopy-->
``````