Control Structure Tutorial

Lua control structures will be familiar to programmers. Sections 2.4.4 and 2.4.5 of the Reference Manual provide the necessary information.

while

The conditional looping statement "while" has the form:

while exp do block end

A simple loop:

We can exit the control of a while statement using the break keyword as in the following example.

repeat

The conditional looping statement "repeat" has the form:

repeat block until exp

A simple loop:

Like the while statement, we can exit a repeat loop using a break statement:

cows_come_home is a variable which is not defined. When we access it we get the value nil, so this code means "until false" or forever.

for

The iterating statement for has two forms. The first is for numerical iteration:

The second is for sequential iteration, e.g. to print the contents of a table. In the example below, 'for' is passed the 'pairs()' iterator function, whose purpose is to supply the values of each iteration:

if ... then ... else ... end

The statement if has the form:

if exp then block { elseif exp then block } [ else block ] end

For example, if ... then ... end

if ... then ... else ... end

if ... then ... elseif ... else ... end

Next Tutorial