制御構造
-
もしそうなら
-
実行しながら繰り返す
-
数値形式
-
ブレーク
-
Goto
もしそうなら
If then Form
if expression then
statements to execute if expression is not false or nil
end
If then else Form
if expression then
statements to execute if expression is not false or nil
else
statements to execute if expression is false or nil
end
If then elseif else Form
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
if headers[name] then
local next_value_index = #(headers[name]) + 1
headers[name][next_value_index] = value
else
headers[name] = {name .. ":" .. value}
end
-
C や Java の場合のように、式は括弧で囲まれていません。
-
C/Java スイッチステートメントと同等のものはありません。同等の処理を行うには、一連の if elseif ステートメントを使用する必要があります。
実行しながら繰り返す
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
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
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
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
sum = 0
for i = 1, #a do -- increment defaults to 1
sum = sum + a[i]
end
ブレーク
sum, i = 0, 1
while true do
if i > #a then
break
end
sum = sum + a[i]
i = i + 1
end
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::
. . .