SoFunction
Updated on 2025-04-12

Lua tutorial (III): Expressions and statements

1. Expression:

    1. Arithmetic operator:
Lua supports conventional arithmetic operators: binary "+", "-", "*", "/", "^" (index), "%" (module), and mono-" (negative sign). All of these operators can be used for real numbers. However, it should be specifically noted that the modulo operator (%) is defined in Lua as:
 

Copy the codeThe code is as follows:

    a % b == a - floor(a / b) * b
 

From this we can deduce that the result of x %1 is the decimal part of x, while the result of x - x %1 is the integer part of x. Similarly, x - x % 0.01 is the result of x being accurate to two decimal places.
    
    2. Relational operators:
Lua supports relational operators: >, <, >=, <=, ==, ~=, and the results of all these operators are true or false.
Operator == is used for equality testing, operator ~= is used for inequality testing. These two operators can be applied to any two values. If the two values ​​have different types, Lua thinks they are not equal. nil value is equal to itself. For table, userdata, and functions, Lua is compared by reference. That is, they are considered equal only when they refer to the same object. like:
Copy the codeThe code is as follows:

a = {}
= 1
= 0
b = {}
= 1
= 1
c = a

The result is a == c, but a ~= b.
For string comparisons, Lua is compared in character order.
    
3. Logical operators:

The logical operators supported by Lua are: and, or and not. Like conditional control statements, all logical operators treat false and nil as false, and other results are true. Like most other languages, and and or in Lua use the "short circuit principle". There is an idiomatic way of writing "x = x or v" in Lua, which is equivalent to: if not x then x = v end. There is also an idiomatic writing method based on the "short circuit principle", such as:
 

Copy the codeThe code is as follows:

    max = (x > y) and x or y
 

This is equivalent to max = (x > y) ? x : y in C. Since both x and y are numeric values, their results will always be true.
    
    4. String concatenation:
The previous blog has mentioned the string concatenation operator (..), and here are some simple examples.
 
Copy the codeThe code is as follows:

    /> lua
    > print("Hello " .. "World)
    Hello World
 

> print(0 .. 1) --Even if the operand of the connection operator is a numeric type, Lua will automatically convert it to a string when executed.
    01

   5. Table constructor:

The constructor is used to build and initialize table expressions. This is a unique expression of Lua and one of the most useful and general mechanisms in Lua. The simplest constructor is the empty constructor {}, which is used to create an empty table. We can also initialize arrays through constructors, such as:

Copy the codeThe code is as follows:

days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
for i = 1,#days do
    print(days[i])
end
--The output result is
--Sunday
--Monday
--Tuesday
--Wednesday
--Thursday
--Friday
--Saturday

From the output results, we can see that days will be automatically initialized after construction, where days[1] is initialized to "Sunday", days[2] is "Monday", and so on.
Another special syntax is also provided in Lua for initializing the record style table. For example: a = { x = 10, y = 20 }, which is equivalent to: a = {}; = 10; = 20
In actual programming, we can also combine these two initialization methods together, such as:

Copy the codeThe code is as follows:

polyline = {color = "blue", thickness = 2, npoints = 4,
    {x = 0, y = 0},
    {x = 10, y = 0},
    {x = -10, y = 1},
    {x = 0, y = 1} }
print(polyline["color"]);
print(polyline[2].x)
print(polyline[4].y)
--The output result is as follows:
--blue
--10
--1

In addition to the above two construction initialization methods, Lua also provides another more general method, such as:

Copy the codeThe code is as follows:

opnames = { ["+"] = "add", ["-"] = "sub", ["*"] = "mul", ["/"] = "div"}
print(opnames["+"])
i = 20; s = "-"
a = { [i + 0] = s, [i + 1] = s .. s, [i + 2] = s..s..s }
print(a[22])

For table constructors, there are two syntax rules that need to be understood, such as:
 
Copy the codeThe code is as follows:

    a = { [1] = "red", [2] = "green", [3] = "blue", }
 

Here we need to note that commas (,) can still be retained after the last element, which is similar to enums in C.
 
Copy the codeThe code is as follows:

    a = {x = 10, y = 45; "one", "two", "three" }
 

You can see that the above declaration has both comma (,) and semicolon (;) element separators, which are allowed in Lua. We usually use semicolons (;) to separate elements of different initialization types. For example, in the example above, the initialization method before the semicolon is the record initialization method, and the subsequent array initialization method.

2. Statement:

    1. Assignment statement:

The assignment statements in Lua are basically the same as other programming languages. The only difference is that Lua supports "multiple assignment", such as: a, b = 10, 2 * x, which is equivalent to a = 10; b = 2 * x. However, it should be noted that Lua needs to calculate the expression on the right of the equal sign before assigning, and then assign the value after each expression has obtained the result. Therefore, we can write variable interaction like this: x,y = y,x. If the number of expressions on the right side of the equal sign is less than the number of variables on the left, Lua will set the value of the extra variable on the left to nil. If the opposite is true, Lua will ignore the extra expressions on the right.

2. Local variables and blocks:

The definition syntax of local variables in Lua is: local i = 1, where the local keyword means that the variable is a local variable. Unlike global variables, the scope of action of local variables is limited to the program block where they are located. The program in Lua can be an executor body, a function executor body or a program block of the control structure, such as:
The following x variable is only valid in the while loop.

Copy the codeThe code is as follows:

while i <= x do
    local x = i * 2
     print(x)
     i = i + 1
end

If it is in interactive mode, when local x = 0 is executed, the program where the variable x is located ends, and the subsequent Lua statement will be regarded as a new program block. If we want to avoid such problems, we can explicitly declare the program block so that even in interactive mode, local variables can still maintain their validity within the block, such as:
Copy the codeThe code is as follows:

do
    local a2 = 2 * a
    local d = (b ^ 2 - 4 * a) ^ (1 / 2)
    x1 = (-b + d) / a2
    x2 = (-b - d) / a2
end  --The scope of a2 and d ends here.

Like other programming languages, try to use local variables if possible to avoid contaminating variable names in the global environment. At the same time, because the validity period of local variables is shorter, the garbage collector can clean them up in time, thereby obtaining more available memory.

   3. Control structure:
The control statements provided in Lua are basically the same as those provided by most other development languages, so here is just a simple list. Then give a detailed introduction to the differences. like:
    1). if then else
 

Copy the codeThe code is as follows:

    if a < 0 then
        b = 0
    else
        b = 1
    end
   

    2). if elseif else then
 
Copy the codeThe code is as follows:

    if a < 0 then
        b = 0
    elseif a == 0 then
        b = 1
    else
        b = 2
    end
   

    3). while
 
Copy the codeThe code is as follows:

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

    4). repeat
 
Copy the codeThe code is as follows:

    repeat
        line = ()
until line ~= "" -- ends until the condition of until is true.
    print(line)
   

    5). for
 
Copy the codeThe code is as follows:

for var = begin, end, step do --If there is no step variable, the default step size of begin is 1.
        i = i + 1
    end
 

It should be noted that the three variables begin, end and step at the beginning of the for loop will be executed only once if they make the expression return value. Another thing is not to modify the value of the variable var in the for loop body, otherwise it will lead to unpredictable results.
    
    6). foreach
 
Copy the codeThe code is as follows:

for i, v in ipairs(a) do  --ipairs is a system function that comes with Lua, which returns an iterator that traverses the array.
        print(v)
    end
   
for k in pairs(t) do      --Print all keys in table t.
        print(k)
    end
 

See the following example code:
 
Copy the codeThe code is as follows:

 days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }
revDays = {}
for k, v in ipairs(days) do
    revDays[v] = k
end

for k in pairs(revDays) do
    print(k .. " = " .. revDays[k])
end

--The output result is:
--Saturday = 7
--Tuesday = 3
--Wednesday = 4
--Friday = 6
--Sunday = 1
--Thursday = 5
--Monday = 2
 

   7). break
It is exactly the same as the break semantics in C language, that is, it breaks out of the innermost loop.