From getting started to giving up Lua -- Statement

Source: Internet
Author: User
Tags define local

From getting started to giving up Lua -- Statement

Lua statements include assignment, control structure, function call, and variable declaration.


An execution unit of lua is called a statement group. A statement group is a string of statement segments that are executed sequentially. Each statement segment can end with a semicolon. In lua, a semicolon is not required to end a statement. You can also press enter to end a statement.

Lua treats a statement Group as an anonymous function with an indefinite parameter. The statement group can define local variables, receive parameters, and return values. Statement groups can be stored in a file or a string of the Host Program. When a statement group is executed, it is first compiled into a sequence of commands in the virtual machine, and then interpreted by the virtual machine to run these commands. Statement groups can also be compiled in binary format. Programs provided by source code and compiled binary programs can be replaced with each other. lua automatically identifies the file type and performs proper processing. (The compilation and conversion details will be explained in the subsequent sections)


Assignment: Lua allows multiple values, for example:

Local x, y = 10, 20; x = 10, y = 20

Local x, y = 10; x = 10, y = nil

Local x, y = 10, 20, 30; at this time, x = 10, y = 20, 30 is discarded.

The principle of multi-value assignment is to assign values from left to right. The right value will correspond to the number on the left, and the excess will be discarded. If not, nil will be used for filling. If the expression list ends with a function call, all values returned by this function will be placed in the right value sequence before the alignment operation. For example

Function getFrame ()

Local x = 0;

Local y = 0;

Local w = 320;

Local h = 568;

Return x, y, w, h;


Local x, y, w, h = getFrame () -- Here x = 0, y = 0, w = 320, h = 568


The assignment section first calculates all the expressions, and then only performs the assignment operation. For example

Local a = {}

Local I = 3

I, a [I] = I + 1, 20

In this example, a [3] is set to 20 without affecting a [4]. Because I in a [I] is taken out before I is assigned 4 (I = 3.

The following expression can be used to exchange two values:

X, y = y, x


You can change the meaning of the global variables and the field assignment operations in the table by using the retriable method. Assign a value to the variable subscript, that is, t [I] = val is equivalent to settable_event (t, I, val ).

The value x = val of global variables is equivalent to _ env. x = val, which is equivalent to settable_event (_ env, x, val ). (The settable_event function is also mentioned in the previous sections. This chapter is just an example and will not be explained in detail)


Control Structure: The control structures in lua include if, while, repeat, and.

While exp do block end

Repeat block until exp

If exp then block {elseif exp then block} else block end

Conditional expressions in the control structure can return any value. Both false and nil are considered false conditions, and other values are considered true (numbers 0 and null strings are also considered true ).

In the repeat-until loop, the ending point of the internal statement block is not in the keyword until, and it also includes other conditional expressions. Therefore, you can use the local variables defined in the loop statement block in the conditional expression.

Return is used to return values from functions or statement groups. Functions and statement groups can return more than one value. For more information, see the preceding getFrame example.

Break is used to end the while, repeat, and for illusion. It ignores the running of the statement segments in the loop and jumps out of the innermost loop.

You can ignore the content in the brackets (return and break can only be detached from the last sentence of a statement block. If you really need to return or break from the middle of the statement block, you can use an explicit declaration of an internal statement block. Generally, it is written as do return end or do break end. This can be done because return or break is the last sentence of a statement block .) This method is not recommended in the coding process.


The for loop has three forms:

For v = var, limit, step do block end

Var is the start value, limit is the end value, and step is the step size. All three control expressions are run only once, and the expression is computed before the loop starts. The results of these expressions must be numbers. You can use break to exit the for loop. Loop Variable v is a local variable in a loop. When the loop ends, v is released. If you want to continue using this value outside the loop, you need to assign this value to a higher-level local or global variable.

Iterator: for namelist in explist do block end is usually used in two ways

For k, v in pairs (explist) do block end

For k, v in ipairs (explist) do block end

The explicit type is table. K and v are the keys and values in the explist table. The explist is calculated only once. It returns three values, one iterator function, one state, and one iterator's initial value. Like above, the iterator can also use break to jump out of the for loop. To retain v, a high-level local or global variable is also required for reference.

Differences between pairs and ipairs:

Pairs can traverse all keys in the table, and can return nil in addition to the iterator itself and the traversal table itself. However, ipairs cannot return nil and can only use the number 0. If it encounters nil, it exits. It can only traverse the first key not an integer in the table.



Local tab = {[3] = "test2", [6] = "test3", [4] = "test1 "}

For k, v in ipairs (tab) do

Print (k, v)



There is no output result, because when key = 1, the value is nil, and no value is output in the jump out loop.


We use pairs to output the same code.


Local tab = {[3] = "test2", [6] = "test3", [4] = "test1 "}

For k, v in pairs (tab) do

Print (k, v)



3 test2
6 test3
4 test1


Let's change the above ipairs example to [3] In the tab table to [1].


Local tab = {[1] = "test1", [6] = "test2", [4] = "test3 "}

For k, v in ipairs (tab) do

Print (k, v)


The output result is obviously 1 test1.


Expression: Lua basic expressions include Arithmetic Operators, Relational operators, logical operators, String concatenation, table constructors, length operators, and functions.

Arithmetic Operators and Relational operators are described in the previous sections.


Logical operators include and, or, and not. Like the conditional operation statement, all logical operators treat false and nil as false, and other results are true. And or are not true or false, but related to two operations.

A and B -- if a is false, a is returned; otherwise, B is returned.

A or B -- if a is true, a is returned; otherwise, B is returned.

For example:

Print (4 and 5) --> 5

Print (nil and 13) --> nil

Print (false and 13) --> false

Print (4 or 5) --> 4

Print (false or 5) --> 5

A very practical technique: assign an initial value v to x if x is false or nil.

X = x or v


If not x then

X = v


And has a higher priority than or.

A? B: c

In lua, we can implement (a and B) or c in this way.

Only false or true is returned for the not result.

Print (not nil) --> true

Print (not false) --> true

Print (not 0) --> false

Print (not nil) --> false


String connection: in lua, two string connections can use two points (...), called the string connection operator. Print ("hello"... "world") --> helloworld

Print (4 .. 5) use numbers of the two number types .. during lua execution, it is automatically converted to a string and the output result is 45. However, note that 45 is no longer of the number type but the string type.


Table constructor: the constructor is used to construct and initialize table expressions. This is a unique expression of lua and one of the most useful and common mechanisms of lua. The simplest constructor is the empty constructor {}, which is used to create an empty table. The constructor can also initialize some data and array initialization methods, such

Days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday "}

Let's print this table.

For I = 1, # days do

Print (days [I]);


Output result:


As shown in the output, days is automatically initialized after being constructed. days [1] is initialized to "Sunday", and so on.

Lua also provides another special syntax used to initialize a table and record the initialization method. For example, a = {x = 10, y = 20} is equivalent to: a = {}; a. x = 10; a. y = 20;

In addition to the preceding two constructor methods, lua also provides a more general method, such:

Opnames = {["+"] = "add", ["-"] = "sub", ["*"] = "mul ", ["/"] = "div "}

Print (opnames ["+"]) --> add

The table constructor has two syntax rules to understand, for example:

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

Note that the end of the last element can still be retained (,), which is similar to the enumeration in C language.

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

We can see that the preceding statement has two element delimiters: (,) and semicolon (;). This method is also allowed in lua. We usually use semicolons (;) to separate elements of different initialization types. In the above example, the initialization before the semicolon is record initialization, and the subsequent method is array initialization.


Get length OPERATOR: We use # above. In lua, # Is the get length operator. The length of a string is the number of bytes. The table length is defined as an integer subscript n. T [n] is not nil and t [n + 1] is nil. In addition, if t [1] is nil, n may be zero. For a regular array, when some non-null values are placed from 1 to n, its length is precise to n, that is, the subscript of the last value. If there is a "empty" in the array (that is, the nil value is clamped between non-null values), # t may be the subscript pointing to any position prior to the nil value (that is, any nil value may be treated as the end of an array ).


Priority: Sort operators in lua in descending order:


     or     and     <     >     <=    >=    ~=    ==     ..     +     -     *     /     %     not   #     - (unary)     ^
You can use parentheses to change the order of operations. The Concatenation Operators (...) and power operators (^) are from right to left. All other operations are left to right.



Function: in lua, the function can be written in the following two ways:

Func = function (params) body end

Function func (params) body end

These two types of writing can be converted to each other, and the latter simply simplifies writing through the syntactic sugar. However, the function structure remains unchanged. It is still the function name, parameter, and return value. You can use (...) to describe a set of parameters in lua, but it must be placed at the end of the parameter list. When a function is called, if the function is not defined as receiving an indefinite parameter, it indicates three points (...) at the end of the parameter list (...), the real parameter list is adjusted to the length of the parameter list. The variable-length parameter function does not adjust the real parameter list. Example:

Function f (a, B) end

F (3) --> a = 3, B = nil

F (3, 4) --> a = 3, B = 4

F (3, 4, 5) --> a = 3, B = 4

Like multi-value assignment, more real parameters are discarded, and less real parameters are filled with nil.

Return can be used in the function. If no return statement is still run at the end of the function, the function will not return any results. You can also think that the nil value is returned by default.

The colon syntax can be used to define a method, that is, a function can have an implicit form parameter self. Therefore, the statement is as follows:

Local meta = {}

Function meta: log (params) body end


Meta. log (self, params) body end

The specific usage and explanation of functions will be described in the following sections. This article only describes some simple usage.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.