"Lua Learning Notes"--types and values, expressions and basic syntax

Source: Internet
Author: User
Tags arithmetic numeric lua table definition

School to go to the devil is a game company internship, the client to use the Lua language, so the winter vacation in the school borrowed "LUA program Design", the book is used to get started very good ~



type and value in Lua, there are the following types:
Types and values, expressions and basic syntax >


in the Lua language, only nil and false are false (false), others are true (true), including 0 and empty strings are also true . Nil in global variables and tables, nil can be removed, a global variable is nil before assignment, a global variable that has been assigned a value, and a variable in the table table is assigned nil, which is equivalent to deleting them:

Types and values, expressions and basic syntax >


Number The values in Lua are not the same as in C/s + +, there are so many types of shapes, floats, and only one type of LUA is number--double. The following are considered number types :

Print (Type (2)) print (Type (
2.2))
print (Type (2e+1))
* Note: The type function in Lua is used to return types of arguments, and the type returned is a string.

stringLua is 8 bytes, so the string can contain any numeric characters, including the embedded 0. The strings in Lua are non-modifiable, and you can create a new variable to hold the string that the user wants:
A = "Hello world"
b = string.gsub (A, "Hello", "HI")
print (a)--Hello World
print (b)--Hi World

The Lua language can be represented by two double quotation marks "", or by two single quotation marks, if there is a double quotation mark in a string that is represented by a double quotation mark, it needs to be represented by an escape character, that is: \ "means"

The escape sequences in Lua are:

Types and values, expressions and basic syntax >


You can also use \DDD (ddd as three decimal digits) to represent letters in a character: "Alo\n123\" "and" \97lo\10\04923 "are the same.

You can also use [[...]] to denote a "piece" of string:

HTML = [[

This form of string can contain multiple lines, can be nested and does not interpret escape sequences, and is ignored if the first character is a line break.

At run time, Lua automatically converts the type between string and number, and when a string uses the arithmetic operator, the string is converted to numbers:

Print ("ten" + 1)-->11
print ("Ten + 1")--+ 1
print ("HI" + 1)-->error

Lua can use ".." to concatenate strings, so:

Print (ten.)-->1020

It's important to note that : The previous number must be the same as: There is a space between them, or the LUA interpreter will think of it as a decimal point


Tonumber () can convert a string to a number, and ToString can convert a number to a string:

Print (tostring) = = "Ten")-->true
print (= = Tonumber (")")-->true


function in the Lua language, function is the first class of values (the same as other variables), meaning that a function can exist in a variable, either as a function parameter or as a function return value. Lua can invoke LUA or C-implemented functions because all of LUA's standard libraries are implemented in the C language.
UserData and Thread UserData is a user-defined data that represents a type created by an application or a C + + language library that can store data (usually structs and pointers) of any data type of any C + + + to Lua Called in a variable.

In Lua, the main thread is the co-program (Coroutine). It is similar to threads, with its own stack, local variables, and instruction pointers, and can share global variables and most other things with other co-programs.

The difference between a thread and a co-worker is that a thread can run multiple times at the same time, and that the process can only run at any one time, and that the running process is suspended only when it is suspended (suspend).
The Table table type implements the associative array, which is very similar to the map in C + +, but the personal feeling is that the "associative array" in LUA is more flexible and better used.   C + + Map<key, value>, is the template class, when implemented, it all the key types are consistent, such as: Std::map<std::string, int> MP; After this, when you insert a pair of "key-value", the type of the key must be of type string (or it can be converted to string by a related function), and the "Associative array" table in Lua does not have this restriction, not only can it be indexed by integers, You can also use a string or other type of value (of course, except nil) to index it. Table does not have a fixed size and can dynamically add arbitrary elements to a table.

In Lua, table is neither "value" nor "variable", but "object". The table is like a dynamic object, and the program holds only one reference (or pointer) to them. There is no need to declare a table in Lua, and in fact there is no way to declare it, we can use "construct expression" to complete a table definition, the simplest is an empty curly brace: {}

A = {}
k = "x"
a[k] =
a[20] = "Hello"
print (a["x"])--
k =
print (a[k])--"Hello"
a["x"] = a["x"] + 1
print (a["x"])--11

Table is always "anonymous" and there is no fixed correlation between a variable holding table and the table itself:

A = {}
a["x"] = ten
B = A--and B and a refer to the same table
print (b["x"])--
b["x"] =
print (a["x"])--> ;
A = nil--and now there's B in reference 
to table B = nil--no more references to table

When there is no longer a reference to a table in a program, the LUA garbage collector will eventually delete the table and reuse its memory.


A = {}
a["x"] = ten
print (a["x"])
--Print (a["y"])--nil

When an element in a table is not initialized, its value is nil. You can also remove this element by assigning nil to an element in the table like a global variable.

The table provides a simpler way to write a a["name", which can be entered directly into the a.name. Therefore, it can be written like this:

a.x = ten
print (a.x)--equivalent to a["x"]
print (A.Y)--equivalent to a["Y"]

It is important to note that a.x and a[x] are not the same, a.x means a["x"], which is indexed by X, while a[x] means to index the value of xIf the value of X is 10, then a[x] denotes a[10].

A = {}
x = "Y"
a[x] = ten
print (A[x])-  -a["y"] field
print (a.x)-  no index
of "X" in nil A Print (A.Y)-10

In Lua5.1, "#" can return the last index value (or its size) of an array or linear table. For example:

For i = 1, ten
	do a[i] = Io.read ()
End
--the above can also be written
for i = 1, ten do
	a[#a + 1] = Io.read ()
end
  --Print read everything for
i = 1, #a do
	print (a[i])
end

Some other uses of #:

Print (a[#a])--Prints the last value of List a
a[#a] = nil--Deletes the last value
a[#a + 1]--adds v to the end of the list


An array is actually a table, and when you use # to calculate the size, there are sometimes unexpected results:

A = {}
a[1] = 1
a[10] =
print (#a)--1

The actual size of the array is 2, because # before the first nil value is calculated, when there is a "gap" in the middle of an array, that is, when the middle contains nil, #就认为数组就这么大了. This may not be the same as our original intention.

We can use the table function MAXN, which returns the maximum number of indexes for a table:

Print (TABLE.MAXN (a))-10

There's a lot of stuff about table, and it's a long argument.


An expression arithmetic operator If A is ten, B is 20: type and value, expression and basic syntax ">


relational operators type and value, expressions and basic syntax >


These operators return TRUE or FALSE. = = and ~= compare two values, if the two value types are different, LUA considers the two different; nil is equal to itself; Lua compares table, UserData, and function by reference, that is, if and only if both refer to the same object.

A = {}; a.x = 1; A.Y = 0
b = {}; b.x = 1; b.y = 0
c = a
print (a = = c)--true references the same object
print (b = = c)--false

Lua compares numbers by traditional numeric sizes and compares strings in alphabetical order.

"0" = = 0--and False
2 <--True
"2" < "--"--false  

The last one is to compare two strings, because "1" is smaller than "2", so "2" should be greater than "15".


logical operator set A is true,b to false "type and value, expression and basic syntax" >


Logic thinks that false and nil are false, others are true, and 0 is true.

A and B-and if A is false, returns a, otherwise returns B

A or B-and if A is true, return B, otherwise return B


Print (4 and 5)-Returns 5
print (nil and 5)-Returns nil
print (4 or 5)-Returns 4
print (false or 5)-5

A useful technique for assigning a to x when x is False or nil

x = x or a

Three-mesh operator A in C language? B:c, in Lua, can be written like this:

(A and B) or C

A is true, the value of (A and B) is B, and C is an OR operation and returns B;

A is false, the value of (A and B) is a, and C is an OR operation, which returns C.


The result of not always returns TRUE or False

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

operator Precedence (high-to-low)

Types and values, expressions and basic syntax >



Basic Syntax Assigning a value is the most basic way to change a variable or table field:

str = "Hello". "World"
T.N = T.N + 1

In the Lua language, you can also assign values to multiple variables, the list of variables and the list of values are separated by commas, and the values to the right of the assignment statements are assigned to the variables on the left:
A, B = ten,--and A is 10,b 20

This feature can be used to exchange operations:
X, y = y, X

The assignment statement calculates all the values on the right, and then assigns the values. When the number of variables and the number of values are different, LUA takes the following strategies: type and value, expression and basic syntax >


The control statement structure is the same as the logical operation, the conditional expression of the control statement considers false and nil false, and the other values are true. The if statement has three forms: 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
While statement while conditions do statements end
Repeat-until Statement repeat statements until conditions

If condition is true, exit the statement.


For statement First Class: value for var = exp1, Exp2, exp3 do Loop-part end
EXP1 is the initial value of var local variable, EXP2 is the terminating value, EXP3 is the step, exp3 default is 1.

Three expressions exp will only be counted once, before the loop begins.


Type II: generic for


①for K, V in Ipairs (t) do print (K. V) End

②for K, V in pairs (t) do print (K. V) End

T is table type


The first type of generic for, which iterates through an array, and the subscript starts at 1 and is an array of contiguous indexed values.

Types and values, expressions and basic syntax >


If the index value is not a number, or is not contiguous, it only prints a contiguous section starting at index 1:

Types and values, expressions and basic syntax >


The second type of generic for can print out all the elements, but the order is irregular:

Types and values, expressions and basic syntax >


It is visible that the order in which it is printed does not appear to be the order we add, because table is implemented with a hash table, and the order and order of the tables that are not in the array form are different.



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.