Lua Tutorial (iii): expressions and statement _lua

Source: Internet
Author: User
Tags arithmetic arithmetic operators logical operators lua polyline

One, expression:

1. Arithmetic operator:
LUA supports regular arithmetic operators: two-dollar "+", "-", "*", "/", "^" (exponent), "%" (modulo), one-dollar "-" (minus). All of these operators are available for real numbers. However, the modulo operator (%) needs to be specifically described, and the operator is defined in Lua as:

Copy Code code as follows:

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

It is possible to push the result of x 1 to the decimal part of X, while the result of x-x% 1 is the integral part of X. Similarly, x-x% 0.01 is the result of X's precision to two digits after the decimal point.

2. Relational operators:
The relational operators that LUA supports are:>, <, >=, <=, = =, ~=, all of which result in true or false.
operator = = for equality testing, operator ~= for unequal testing. These two operators can be applied to any two values. If two values are of different types, Lua thinks they are unequal. The nil value is equal to itself. For table, UserData, and functions, LUA is compared by reference. In other words, they are considered equal only when they reference the same object. Such as:
Copy Code code as follows:

A = {}
a.x = 1
A.Y = 0
b = {}
b.x = 1
B.Y = 1
c = A

The result is a = = C, but a ~= B.
For a comparison of strings, Lua is compared by character order.

3. Logical operators:

The logical operators that LUA supports are: and, or, and not. As with conditional control statements, all logical operators treat false and nil as false, and other results are true. Like most other languages, the and and or in Lua uses the "short-circuit principle." In Lua there is an idiomatic phrase "x = x or V", which is equivalent to: if not X then x = v-end. There is also an idiom based on the "short-circuit principle", such as:

Copy Code code as follows:

max = (x > Y) and x or Y

This is equivalent to Max = (x > Y) in the C language? X:y. Because both X and Y are numeric, their results will always be true.

4. String connection:
The previous blog has mentioned the string concatenation operator (..), and here are some simple examples.
Copy Code code 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 still automatically convert it to a string at execution time.
01

5. Table Builder:

An expression that the constructor uses to build and initialize the table. This is a LUA-specific expression and is one of the most useful and versatile mechanisms in Lua. One of the simplest constructors is the empty constructor {}, which is used to create an empty table. We can also initialize an array through the constructor, such as:

Copy Code code 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, it can be seen that days after construction will be automatically initialized, where Days[1] is initialized to "Sunday", days[2] to "Monday", and so on.
LUA also provides another special syntax for initializing a record-style table. such as: a = {x = ten, y = 20}, which is equivalent to: a = {}; a.x = 10; A.Y = 20
In actual programming, we can also combine the two initialization methods, such as:

Copy Code code as follows:

polyline = {color = "blue", thickness = 2, npoints = 4,
{x = 0, y = 0},
{x = ten, y = 0},
{x = -10, y = 1},
{x = 0, y = 1}}
Print (polyline["color"]);
Print (polyline[2].x)
Print (POLYLINE[4].Y)
--The output results are as follows:
--blue
--10
--1

In addition to the two construction initialization methods, LUA offers a more general approach, such as:

Copy Code code 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 the constructor of the table, there are two grammatical rules to understand, such as:
Copy Code code as follows:

A = {[1] = "Red", [2] = "Green", [3] = "Blue",}

Notice here that the last element can still retain the comma (,), which is similar to the enumeration in the C language.
Copy Code code as follows:

A = {x = ten, y = 45; "One", "two", "three"}

You can see that there are commas (,) and semicolons (;) two element delimiters in the above declaration, which is allowed in Lua. We typically use semicolons (;) to separate elements of different initialization types, such as initialization before semicolons in the preceding example, and the latter is an array initialization method.

Second, the statement:

1. Assignment statement:

The assignment statements in Lua are essentially the same as other programming languages, the only difference being that LUA supports "multiple assignments", such as: A, b = 2 * x, which is equivalent to a = 10; b = 2 * x. It should be explained, however, that LUA needs to evaluate the expression to the right of the equal sign before assigning the value, and then assign the result after each expression. So we can write variable interactions like this: X,y = y,x. If the number of expressions to the right of the equal sign is less than the number of left variables, LUA will place the value of the extra variable on the left to nil, and in contrast, LUA ignores the more-than-right expression.

2. Local Variables and blocks:

The local variable definition syntax in LUA is: local i = 1, where the Locals keyword indicates that the variable is a partial variable. Unlike global variables, the scope of a local variable is limited to the program block in which it resides. A program in LUA can be a control structure's execution body, function execution body, or a program block, such as:
The following x variable is valid only within a while loop.

Copy Code code as follows:

While I <= X does
Local x = i * 2
Print (x)
i = i + 1
End

In interactive mode, after the local x = 0 is executed, the program that contains the variable x ends, and the following LUA statement is treated as a new program block. If you want to avoid this type of problem, we can explicitly declare the block so that even in interactive mode, the local variable still retains its block validity, such as:
Copy Code code as follows:

Todo
Local A2 = 2 * A
Local D = (b ^ 2-4 * a) ^ (1/2)
X1 = (b + d)/A2
x2 = (-b-d)/A2
The scope of end--A2 and D is thus concluded.

As with other programming languages, if it is possible to use local variables as far as possible, so as not to cause the global environment variable name pollution. At the same time, because the local variable has a shorter validity period, the garbage collector can clean it up in time to get more available memory.

3. Control structure:
The control statements provided in LUA are essentially the same as those provided by most other development languages, so this is just a simple enumeration. Then give a detailed description of the difference section. Such as:
1). If then else

Copy Code code as follows:

If a < 0 Then
b = 0
Else
b = 1
End

2). If ElseIf else then
Copy Code code as follows:

If a < 0 Then
b = 0
ElseIf A = = 0 Then
b = 1
Else
b = 2
End

3). while
Copy Code code as follows:

Local i= 1
While A[i] do
Print (A[i])
i = i + 1
End

4). Repeat
Copy Code code as follows:

Repeat
line = Io.read ()
Until line ~= ""--until until's condition is true.
Print (line)

5). for
Copy Code code as follows:

for var = the begin, end, and step does--if there is no steps variable, the default stride length of Begin is 1.
i = i + 1
End

What you need to note is that the three variables begin, end, and step at the beginning of the for loop, and if they make the return value of the expression, the expression executes only once. Then there is not to modify the value of Var in the For loop body, otherwise it will cause unpredictable results.

6). foreach
Copy Code code as follows:

For I, V-ipairs (a) do--ipairs is a LUA self-contained system function that returns an iterator that iterates through an array.
Print (v)
End

For k in pairs (t) does-prints all keys in table T.
Print (k)
End

See the following sample code:
Copy Code code as follows:

Days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
Revdays = {}
For K, v. in Ipairs
REVDAYS[V] = k
End

For K-in pairs (revdays) todo
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
and C language break semantics exactly the same, that is, jump out of the most inner loop.

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: info-contact@alibabacloud.com 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.