Control structures


If

Structure:

if condition then
  block
elseif condition2 then
  block
elseif condition3 then
  block
else
  block
end

If one elseif is true, execution exits the if loop without checking the subsequent elseifs.

Example

if 3 < 2 then
    print("bigger")
    elseif 5 > 3 then
        print ("small")
    elseif 4 > 2 then
        print ("never gets here")
    else
        print ("here neither")
end


small

Anything that does not return false or nil is considered true to Lua. So, an expression like: if 5 then print("ok") end will print "ok".

while

Structure:

while condition do
  block
end

Example:

i= 1
while i <= 5 do
    print(i)
    i= i + 1
end


1
2
3
4
5

repeat

Structure:

repeat
  block
until condition

Example:

i= 1
repeat
    print(i)
    i= i + 1
until i == 5
1
2
3
4

for

numeric:

Structure:

for variable = start, stop, step do
  block
end

Examples:

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


5
6
7
8
9
10
for i = 5,10,2 do
    print(i)
end


5
7
9

in pairs & in ipairs

As far as I know, they are used in tables and arrays. pairs will follow whatever order it finds in the table, while ipairs will follow a crescent order of indexes (mostly for arrays). pairs and ipairs are called "iterators".

Structure:

for var1, var2, var3 in iterator(table) do
  block
end

Example:

t= {2, 4, 6, "house"}
for x, y in ipairs(t) do
    print(x, y)
end


1    2        -- first is the key, then the value
2    4        -- since this is an array, the first
3    6        -- is the index
4    house

break

Break exits the current loop.

results matching ""

    No results matching ""