Flow Control

You can use two minus signs – the next is the comment, which is not processed as code

if/else

Conditional judgment syntax, followed by true or false values, such as nil/false are false values, other values are true values, and else the code that is executed without satisfaction is an optional statement, for example

var a = {}
if false then
    print('false')
elseif nil then
    print('ni')
elseif 2 > 1 then
    print('2>1')
elseif a then
    print('a')
else
    print('else')
end

or
if a then
    print('a')
end

for

Iteration statements

There are two usages, the first is ‘for v = e1, e2 and e3 do block end’, the initial value of e1 is v, e2 is the end of the v value (ends when v > e2), e3 is to increase the value of the each loop of v, e3 can be negative and optional, default is 1

Such as

for v=1,10,2 do
    print(v)
end

Another usage is ‘for var_1, ··· var_n in f, step do block end’, var_1 to var_n is a serial of variable names for loops, The values of step and var_1 to var_n are passed to the function f at each loop, and the result is given to var_1… , var_n. Until f(step, var_1,…var_n) return the nil value,

Such as

var a

let f = function(s: number, v: number)
    if not v then
        return 1
    elseif v > 10 then
        return nil
    else
        return v + s
    end
end

for a in f, 2 do
    print(a)
end

let t1 = [1,2,3]
for k: int, v: int in pairs(t1) do   -- The pairs here are used to traverse the Map<T>, Array<T>, global function of table, and iterate by key
    pprint(k, v)
end

while/break

The syntax structure ‘while exp do block end’, To satisfy the exp condition the block code block can be continued, and the break statement can be used to break out of the loop

Such us

var a = 1
while a < 10 do
    a = a + 1
    print(a)
    if a > 8 then
        break
    end
end

repeat

The syntax structure ‘repeat block until exp’, repeating the block’s code block until it satisfies the exp is true, and the break statement can also be used to break out of the loop

Such as

local a = 1
repeat
    a = a + 1
    print(a)
until a >= 10

and

The logical operator, if the right and left two expressions are true values, the result is true, for example, true and false will be false, true and true will be true

or

The logical operator, the left and right two expressions have a true value, and the result is the truth value, such as true of false, which is true, false or false is false

not

Logical operators, contrary to the Boolean value of the expression on the right, such as the not false value is true