Lua Basic Tutorial Assignment statements, expressions, Process Control, function learning notes _lua

Source: Internet
Author: User

Assignment statement

Note, the single line is represented by (-), Multiline (--[[...]) To mark;
Definition, which is not defined in LUA (declaring the data type), it is assigned a value to determine its data type.
Assignment is the most basic way to change the value of a variable and change the table field. A = "Hello". "World"

Lua can assign values to multiple variables, and the variables list and value list elements are separated by commas, and the value on the right side of the assignment statement is assigned to the variable on the left in turn. A, B = ten, 2*x <--> a=10; B=2*x

Lua, which encounters an assignment statement, evaluates all the values on the right before performing an assignment, so we can exchange the values of the variables:

Copy Code code as follows:

X, y = y, x--swap ' x ' for ' y '
A[i], a[j] = A[j], A[i]--swap ' a[i ' for ' a[i '

When the number of variables and values are inconsistent, LUA will always take the following strategies based on the number of variables:

A. The number > value of the variables is supplemented by the number of variables nil B. The number of variables < values of the extra value will be ignored
Multivalued assignments are often used to exchange variables or return function calls to variables: A, B = f ()--f () returns two values, the first is assigned to a, and the second is assigned to B.

An expression

An expression---an expression requires an operator.

1. Arithmetic operator: +-*/^ (subtraction power, two-element operator),-(negative, unary operator); operation is the same as C + +
2. Relational operators:<, >, <=, >=, = =, ~= (not equal); These operators return the result to False or true;== and ~= compare two values, and if two value types are different, Lua thinks the two are different; nil is only equal to himself. Lua compares tables, UserData, and functions by reference. That is, it is equal if and only if both represent the same object.

Copy Code code as follows:

Print ((2 <))--true
Print (("1" = = 1))--false
Print (("2" > ")--true
a={};a.x=1;a.y=0;
b={};b.x=1;b.y=0;
Print ((a ~= b)); --true
c = A;
Print ((a = = c)); --true
--lua comparison numbers are performed in the traditional numeric size, and the strings are compared in alphabetical order, but the alphabetical order depends on the local environment.
-In order to avoid inconsistent results, a mixture of comparison numbers and strings, LUA will make an error, such as: 2 < "15"

3. Logical operators: And, or, not; logical operators think false and nil false (false), others true, and 0 is true.
The operations of and and or are not true and false, but are related to its two operands. A and B-if a is false, return a, otherwise return B; A or B-if A is true, return a, or return B; Think of the stack, if the first variable can be judged true and false, you do not need to judge the second variable.

and has a higher precedence than or.

The ternary operator in the C language, a? B:C ==>> can be implemented in LUA: (A and B) or C
The result of not always returns false or True

Copy Code code as follows:

Print (not nil)--> true
Print (not false)--> true
Print (not 0)--> false
Print (not not nil)--> false

4. Connection operator:.. (Two dots); If the operand is a number, Lua turns the number into a string.

Copy Code code as follows:

Print ("Hello" ...) World ")--> Hello World
Print (0.. 1)--> 01

Process Control

The conditional expression result of the control structure can be any value, and Lua considers false and nil false and other values as true.
Do.. End (equivalent to C + + {})

If statement, there are three different forms

Copy Code code as follows:

If conditions then
Then-part
End
If conditions then
Then-part
Else
Else-part
End
If conditions then
Then-part
ElseIf conditions Then
Elseif-part
.. ---> Multiple ElseIf
Else
Else-part
End

Because LUA does not support switch statements, this series of If-else if codes is common.

While statement

Copy Code code as follows:

While condition do
statements;
End

Repeat-until statement

Copy Code code as follows:

Repeat
statements;
until conditions;

The conditional judgment is done after the loop body, so the loop body executes at least once. Similar to C + +, do ... while ()

For statement

Numeric for (number for)

Copy Code code as follows:

For VAR=EXP1,EXP2,EXP3 do
Loop-part
End
--for will use EXP3 as step from EXP1 (initial value) to EXP2 (terminating value) to execute loop-part. Where exp3 can be omitted, default Step=1

generic for (generic for), the generic for loop traverses all values through an iterator (iterator) function class.

Copy Code code as follows:

--Print all values of array a
For i,v in Ipairs (a) doing print (v) end

Lua's underlying library provides ipairs, a iterator function for traversing arrays. In each loop, I is given an index value, while V is given a value to the array element that should be indexed.

Copy Code code as follows:

Let's look at an example that iterates through the table key:
--Print all keys of table ' t '
--for k in pairs (t) does print (k) End

Days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
Revdays = {}
For i,v in pairs
REVDAYS[V] = i--revdays = {["Sunday"] = 1, ["Monday"] = 2,["Tuesday"] = 3, ["Wednesday"] = 4,["Thursday"] = 5, ["Friday" ] = 6,["Saturday"] = 7}
End
--x = "Tuesday"
--print (Revdays[x])--3

For k in pairs (days) does print (k) End--1234567
For K-in pairs (revdays) does print (k) End

The standard library provides several iterators, including for each row in the iteration file (io.lines), the iteration Table element (pairs), the iteration group Element (ipairs), the word (string.gmatch) in the iteration string, and so on.

Break and return statements

Function

Copy Code code as follows:

function foo (A, B, c)
Local sum = a + b
Return sum, C--function returns multiple values
End
R1, r2 = foo (1, ' 123 ', ' hello ')--parallel assignment
Print (r1, r2)--124 Hello

function definition: Defines functions with keyword function, ending with keyword end
Local variables: Defined with the key word. If you do not use the local definition, even variables defined within the function are global variables!
Functions can return multiple values: Returns a, B, C, ...
Parallel assignment: A, B = C, D
Global variables: The preceding code defines three global variables: foo, r1, and R2

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.