Study notes on Lua expressions and control structures

  • 2020-05-05 10:54:51
  • OfStack

arithmetic operator

The arithmetic operators of Lua are:

"+" (addition) :


print(1 + 2)

"-" (subtraction) :


print(2 - 1)

"*" (multiplication) :


print(1 * 2)

"/" (division) :


print(1 / 2)

"^" (exponent) :


print(27^(-1/3))

"%" (take module) :


print(5 % 3)

relationship operator

Lua provides the following relationship operator:


< > <= >= == ~=

The results of the operations returned by the above operators are true or false. Strings and Numbers cannot be compared

logical operator

The logical operators are and, or, not


print(1 and 2)
print(nil and 1)
print(false and 2)
print(1 or 2)
print(false or 5)

The logical operators treat false and nil as false and the others as true.

local variables and scope

Lua creates local variables with the local statement, and local variables are scoped only to the block in which they are declared.


local a, b = 1, 10
if a < b then
    print(a)
    local a
    print(a)
end
print(a, b)

Storing global variables with local variable local speeds up access to global variables in the current scope. For the effect of acceleration, compare the execution time of the Fibonacci sequence (Fibonacci) calculated below:


function fibonacci(n)
    if n < 2 then
        return n
    end
    return fibonacci(n - 2) + fibonacci(n - 1)
end
io.write(fibonacci(50), "\n")

Use the local variable local


local function fibonacci(n)
    if n < 2 then
        return n
    end
    return fibonacci(n - 2) + fibonacci(n - 1)
end
io.write(fibonacci(50), "\n")

control structure

if then elseif else end


if num == 1 then
    print(1)
elseif num == 2 then
    print(2)
else
    print("other")
end

Lua does not support the switch statement

while

Judge the while condition first, if the condition is true, then execute the loop body, otherwise end


local i = 1
while a[i] do
    print(a[i])
    i = i + 1
end

repeat-until

Execute the loop body once, then judge the condition, if the condition is true then exit the loop body, otherwise continue to execute the loop body. Similar to do-while statements in other languages, the body of the loop executes

at least once


local a = 1
repeat
    a = a + 1
    b = a
    print(b)
until b < 10

for loop

There are two types of for statements: digital for (numeric for) and generic for (generic for)

Number for syntax:


for start, end, step do
    doing something
end

start is the start value, end is the end value, step is the step size (optional, default is 1)


for a = 10, 0, -2 do
    print(a)
end

The generic for loop traverses all values through an iterator (iterator) function:


tab = { key1 = "val1", key2 = "val2", "val3" }
for k, v in pairs(tab) do
    if k == "key2" then
        break  
    end
    print(k .. " - " .. v)
end

The break and return statements are used to jump out of the currently executing block.


Related articles: