Control structure

In Lua, the control structure is very simple: if is used to judge conditions,while,repeat is used to loop statements, and for can be used to iterate over tables or loop. All control structures must be displayed with the end keyword.

if

if 1 > 0 then
    print(1)
else
    print(0)
end
-- -- > 1
Copy the code

You can also write elseif

a = 10
if a < 5 then 
    print('a > 5')
elseif a >= 5 and a <= 10 then
    print('a>= 5 & a <= 10')
end
Copy the code

Note that else is not required. You can just say if and end.

while

While is used for looping. See an example

a = 1
while(a < 10) do
    print(a)
    if a == 5 then break end
    a = a+1
end
Copy the code

for

Used as a cycle:

for i = 1.10 do 
    print(i)
end
Copy the code

This one goes from 1 to 10;

There is also a new growth step that we often use. Let’s take a look:

for i = 1.10.2 do 
    print(i)
end
Copy the code

The 2 here means that after each loop, I increases by 2

Traversing the table:

t = {'aa'}
for k,v in ipairs(t) do
    print(k .. v)
end
--> 1aa
Copy the code

Of course, you can also use an if statement in a for statement, and you can use the break keyword to break out of the loop.

for i = 1.10 do 
    print(i)
    if i == 5 then 
        print('a==5')
        break 
    end
end
Copy the code