Explanation of basic data types, expressions and process control statements in Lua


1. Luatype
1.1 basic types

Lua is a dynamically typed language with no type defined syntax. Lua has 8 basic types: Nil (empty), Boolean (Boolean), number (number), string (string), UserData (custom type), function (function), thread (thread) and table (table).

Function type can return its type name (string) according to a value, such as print (type (print)), and output “function”; Print (type (type (x))) and output “string”. (here, type (x) always returns a string whether x is defined or not)

1.2 points for attention of various types

About Boolean:

In Lua, false and nil are regarded as “false”, and other values are regarded as “true” (including the number 0 and empty string).
About number:

This type is used to represent real numbers (double precision double), and integers are also represented by this type.
About string:

A character string cannot be modified directly like C language. If necessary, a new string should be created through the string library. A string can be delimited by a pair of matching single or double quotation marks. The escape sequence of C-like language can be used.

In addition, it can be defined by brackets [[content]], in which the newline characters are ignored and applicable to a string containing an entire paragraph. If any number of equal signs are added between the two square brackets on the left, such as [= = [, the square brackets with the same number of equal signs should be matched on the right of the string, such as] = =]. In this way, any content string can be directly embedded without escape. Similarly, annotations can also be used in this way, such as — [= = [match –] = = =].

Lua provides automatic conversion of numbers and strings at run time. For example, print (“10” + 1) – > 11, print (10.. 20) – > 1020 (“…” is a string connector. In the above example, the number is converted into a string and connected, and a space should be left between the number and.

It is recommended to minimize the use of automatic conversion, and force conversion can be used if necessary. The function ToNumber (x) attempts to convert x to a number, returns nil if it fails, and the function toString (x) converts x to a string. Put “#” before the string to obtain the length of the string, such as print (# “length”) – > 6.
About table:

Table is an array with special index mode. It can use other types of values except nil as indexes. Its growth and deletion are completed through automatic memory management. Table is an “object”. The program only holds a reference to them. For example, you can create a table through a = {} and store its reference to A. if B = a, B and a reference the same table. If an element of table is not initialized, its value is nil. You can delete an element of table by assigning nil.

There is an equivalent expression: P [“age”] is equivalent to p.age. Note that P. age and P [age] are not equivalent.

“#” can be used to return the last index value (or its size) of an array. For example, print (a [#a]) prints the last value of list a, and a [#a + 1] = io. Read() reads a value and inserts it at the end of list a. Note that Lua uses nil as a flag to define the end of an array. When an array contains nil in the middle, # it will be considered that the first nil is the end. Therefore, avoid using # for arrays with “gaps”.

In Lua, the first index of the table is generally 1 by default instead of 0 in C language.
Function, UserData, and thread types are left for later.
2. expression
2.1. Arithmetic operator

Conventional operators are: + add, – subtract, * multiply, / divide, ^ exponent,% modulo. Where ^ can be used for any real number, such as x ^ (- 1 / 3) to calculate the reciprocal of the cube root of X It can be used as follows: X% 1 is the decimal part of X, and X – x% 0.01 is the result of X accurate to two decimal places.

2.2. Relational operators

General relational operators include: < less than, > greater and, < = less than or equal, > = greater than or equal, = = equal, ~ = unequal== And ~ = can be used for any two values. If the two values have different types, they are not equal. If they have the same type, they are compared normally (NIL is only equal to itself). For objects, their references are compared.

2.3. Logical operators

The logical operators are and, or, and not. For and (or), if the first operand is false (true), the first operand is returned; otherwise, the second operand is returned. For example, print (4 and 5) – > 5, print (false or 5) – > 5.

There are some common ways to write: x = x or V, which can be set as a default value v when x is not set. Another way of writing (A and b) or C is similar to a? B: C, such as max = (x > y) and X or y.

2.4. String connector

You can use “..” (two points) to connect two strings. If either of them is a number, Lua will automatically convert, such as print (0.. 1) – > 01. The connection string will only create a new string and will not modify the original operand.

The priority order of lua operators is shown in the following figure.

Explanation of basic data types, expressions and process control statements in Lua

2.5. Table construction formula

In addition to the above direct assignment of {} to create an empty table, its value can be initialized, such as day = {“s”, “m”, “t”}, or point = {x = 10, y = 20} (i.e. point. X = 10, point. Y = 20). The above two initialization methods can be mixed, and semicolons can be used instead of commas to clearly separate the list part from the record part, such as polyline = {color = “blue”; {x = 0, y = 0}, {x = 10, y = 10}, {x = 20, y = 30}, then print (polyline [2]. X) ` – > 10.

For a more general initialization format, you can declare the index value between square brackets, such as opnames = {[“+”] = “add”, [“-“] = “minus”}. If you really need to use 0 as the starting index of an array in some cases, you can do this: days = {[0] = “s”, “m”, “t”}. However, it is not recommended to use 0 as the index starting value in Lua, because most built-in functions assume that the array starts at index 1.

3. Sequential structure
3.1. Assignment

In addition to the ordinary “=” assignment, Lua also allows multiple assignments, and each value and each variable are separated by commas. Lua always adjusts the number of values on the right of the equal sign to be consistent with the number of variables on the left. If the number of values is less, the redundant variables will be given nil; If there are too many values, the extra values will be discarded. For example, a, B = 10, 2 * x, x, y = y, X (exchange). Multiple assignment is generally used to exchange the values of two variables or accept multiple return values of a function.

3.2. Local variables and program blocks

Compared with global variables, Lua also provides local variables. Add the upper bound determiner local to the variables. The scope of local variables is limited to the program block that declares them (such as the executor of the control structure, function, etc.).

Note that in interactive mode, each line of input itself forms a program block, so a single local declaration has no effect. You can explicitly define a block and put the content into a pair of do end keywords. This method can also be used to strictly control the scope of some local variables.

There is a common way to write local foo = foo. Create a local variable Foo and initialize it with the value of the global variable foo. If other subsequent functions change the value of the global variable foo, you can save it here first.

4. Control structure
All control structure statements have a displayed Terminator: if, for, and while end, and repeat end until.

4.1. If then else (else if) statement

Format: if < condition1 > then < content1 > else if < condition2 > then < content2 > else < content3 > end
Switch statements are not supported in Lua, so a series of if else if statements are common.

4.2. While and repeat statements

Format: while < condition > do < loop body > end

Format: repeat < loop body > until < condition >
In Lua, the scope of a local variable declared in the loop body includes the conditional test of the loop.

4.3. Numeric for statement

Format: for VAR = Exp1, exp2, EXP3 do < loop body > end
The above formula indicates that VaR changes from Exp1 to exp2 and increases VaR in steps of EXP3. Where EXP3 is optional. If not specified, the default step size is 1. If exp2 is set to math.huge, it is an infinite loop.

There are some details to pay attention to. The three expressions of for are evaluated at one time before the start of the loop and will not be evaluated in the future. In addition, the control variable is automatically declared as a local variable of the for statement, which is only visible in the loop body.

4.4. Generic for statement

The generic for loop traverses all values through an iterator, such as for I, V in ipairs (tableA) do print (V) end, where I is given an index value and V is given a corresponding element value. The ipairs (array) function is used to traverse the array and return the numeric subscript element value pair, the pairs (table) function is used to traverse the table and return the key value pair, and string.gmatch (string) iterates the words in the string.

One application of the generic for is to create an inverse table, that is, the key value of the new table is reversed from the key value of the original table.

4.5. Break and return statements

Both statements are used to jump out of the current statement block, break to end a layer of loop, and return to end the execution of a function. If you have just defined a function and directly want to jump out of the function at the beginning as a call, you can use a displayed do block to contain the return statement, that is, function foo() do return end.