Control structures
-
If Then Else
-
While Do and Repeat Until
-
Numeric For
-
Break
-
Goto
If Then Else
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
-
The expression is not enclosed in parentheses as is the case in C and Java.
-
There is no equivalent to the C/Java switch statement. You have to use a series of if elseif statements to do the equivalent.
While Do and Repeat Until
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.
Numeric For
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
Break
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::
. . .