Lua Tutorial (ii): basic knowledge, type and value introduction _lua

Source: Internet
Author: User
Tags data structures numeric lua reserved

First, the basic knowledge:

1. First Program and function:
in the current learning phase, the best way to run a LUA program is through LUA's own interpreter programs, such as:

Copy Code code as follows:

/> Lua
> Print ("Hello World")
Hello World

This allows us to enter the LUA code interactively and get the execution results immediately. This is really handy for testing programs with fewer code blocks, but this is not a good way for relatively complex programs. If so, we can save the LUA code in a separate LUA program file, and then execute the LUA code in the file as command-line arguments through the LUA interpreter program. If we save the following LUA code to a Test.lua file:

Copy Code code as follows:

function fact (n)
if n = = 0 Then
Return 1
Else
return n * Fact (N-1)
End
End
Print ("Enter a number:")
A = Io.read ("*number")
Print (Fact (a))

Copy Code code as follows:

/> Lua D:/test.lua
Enter a number:
4
24

2. Code specification:

1. Lua's multiple statements do not require any delimiters, such as the C-language semicolon (;), where the newline character also does not act as a statement separator. Therefore, the following wording is legal. Such as:

Copy Code code as follows:

A = 1
b = A * 2

A = 1;
b = A * 2;

A = 1; b = A * 2;
A = 1 B = A * 2

2. Use the Dofile () method to refer to functions in other LUA files, such as:

Copy Code code as follows:

function fact (n)
if n = = 0 Then
Return 1
Else
return n * Fact (N-1)
End
End

Save the above function to the Test2.lua file.

Copy Code code as follows:

/> Lua
> Dofile ("D:/test2.lua")
> Print (Fact (4))
24

3. Lexical specification.
As in most other languages, when declaring a variable, a variable name can consist of any letter, number, and underscore, but cannot begin with a number. There is also a special rule in Lua, this is preceded by an underscore (_) followed by several uppercase letters (_version), which are generally reserved and used for special purposes by LUA, so we need to avoid such declarations when declaring variables, so as not to cause unnecessary trouble to later maintenance.
Lua is case sensitive, so be particularly careful with the use of some LUA reserved keywords, such as and. But and and and are not Lua's reserved words.
4. There are two types of annotations in Lua, one is a single-line comment, such as:
Copy Code code as follows:

--this is a single line comment.
Another is a multiline comment, such as:
--[[
This is a multi-lines comment.
--]]

3. Global variables:
Global variables do not need to be declared in Lua and can be assigned directly. If you access an uninitialized global variable directly, LUA will not complain and return directly to nil. If you do not want to use the global variable again, you can set it directly to nil. Such as:
Copy Code code as follows:

/> Lua
> Print (b)
Nil
> b = 10
> Print (b)
10
> b = Nil
> Print (b)
Nil

4. Interpreter Program:
The command line usage is as follows:
LUA [Options] [lua-script [arguments]]
There are 3 main command-line options for this tool:
-E: You can execute the LUA code directly on the command line, such as: Lua-e "print" (\ "Hello world\") "
-L: The LUA library file that is loaded with this option, such as: Lua-l mylib-e "x = 10", which loads the LUA code in Mylib into memory before executing, can use the LUA function defined in the file directly in the following command.
-I: After executing the specified LUA program file, it does not exit the interpreter program, but instead goes directly to the interactive mode of the program.
In the interactive mode of the interpreter program, we can directly output the execution result of an expression by adding an equal sign (=) identifier before the expression. In this way, we can use the program for calculators, such as:
Copy Code code as follows:

/> Lua
> = 3 + 1 + 4
8

The end of this section is to describe the command-line parameter access rules for the LUA script. Such as:
Copy Code code as follows:

/> Lua Lua-script.lua a b C

At the program entry point of the script, the LUA interpreter creates a table named Arg with all command-line arguments. where the script name (Lua-script.lua) is located at the 0 location of the table index. Its first argument (a) is at index 1, and so on. This index is the same as the rules for reading command line arguments in the C language. But the difference is that LUA provides a negative index to access command-line arguments before the script name, such as:
Copy Code code as follows:

ARG[-1] = Lua
Arg[0] = Lua-script.lua
ARG[1] = a
ARG[2] = b
ARG[3] = C

Ii. Type and value:

Lua is a dynamically typed language. The language itself does not provide the syntax for the type definition, and each value "carries" its own type information. There are 8 basic types in Lua, respectively: nil, Boolean, number, string, UserData, function, thread, and table. We can get the type information of a variable by using the type function, which is returned as a string. Such as:

Copy Code code as follows:

> Print (Type ("Hello World")
String
> Print (Type (10.4))
Number
> Print (Type (print))
function
> Print (Type (true))
Boolean
> Print (Type (nil))
Nil
> Print (Type (X))
String

1. Nil (empty):
Nil is a type that has only one value nil, and its main function is to distinguish any other value. As previously mentioned, the default value of a global variable before the first assignment is nil, and assigning nil to a global variable is equivalent to deleting it. Lua uses nil to represent an "invalid value" scenario.

2. Boolean (Boolean):
The type has two optional values: false and True. In Lua only when the value is false and nil, the other values are considered true, such as the numeric zero and the empty string, which is different from the C language.

3. Number (digit):
Number in Lua is used to represent real numbers. There are no specialized types in Lua that represent integers.

4. String (strings):
Strings in Lua typically represent "one character sequence". A variable of string type is immutable, so it is not possible to modify one character of the string as directly as in C, but to create a new string while modifying it. Such as:
Copy Code code as follows:

1 A = "one string"
2 B = string.gsub (A, "one", "another")
3 Print (a)
4 print (b)
/> Lua D:/test.lua
One string
Anotner string

LUA supports a sequence of word escape similar to the C language, as shown in the following table:

In Lua, [[All strings]] can also be used to disable [[]] a literal character, such as:
page = [[If two square brackets contain such content: A = B[c[i], this will lead to the LUA misunderstanding, so in this case, we can change it to [===[and]===], thus avoiding the occurrence of misunderstanding.
LUA provides an automatic conversion of numbers and strings at run time. Such as:

Copy Code code as follows:

> Print ("10" + 1)
11
> Print ("10 + 1")
10 + 1

If in actual programming, you do not want two numeric strings to be automatically converted, but to implement the connection between strings, you can pass "... "Operator to complete. Such as:
Copy Code code as follows:

> Print (10.. 20)
1020

Attention.. There must be a space between the numbers on either side, or the LUA misunderstanding will be the decimal point.
Although LUA provides this kind of automatic conversion functionality, it avoids some unpredictable behavior, especially because of the inconsistent behavior caused by the LUA version upgrade. For this reason, it should be possible to use a display conversion, such as a string-Tonumber function (), or the function ToString () of a number-spin string. For the former, if the function argument cannot be converted to a number, the function returns nil. Such as:
Copy Code code as follows:

line = Io.read ()
n = tonumber (line)
if n = = Nil Then
Error (line. ' Not ' a valid number ')
Else
Print (n * 2)
End

The last thing you need to introduce about LUA's string is the "#" identifier, which returns the length of the string after the string variable, such as the following:

Copy Code code as follows:

1 a = "Hello"
2 Print (#a)
/> Lua D:/test.lua
5

5. Table (tables):

We can treat the table type in LUA as an associative array, such as a map in the C + + standard library, except that the key (key) of a table in Lua can be any type (excluding nil), whereas a key in the map can only be a modal parameter type. In addition, the table has no fixed size and can dynamically add any number of elements to a table. The table, the most important data structure in Lua, is powerful and can be used to implement arrays, collections, records, and queue data structures. The following is a variable declaration for table and how the associated data is initialized:

Copy Code code as follows:

A = {}--Creates a Table object and stores its reference to a
K = "X"
A[K] = 10--Creates a new entry, key = "X", value = 10
A[20] = "great"-new entry, key =, value = "Great"
Print (a["x"])
K = 20
Print (A[k])--Printing great
a["x"] = a["x"] + 1
Print (a["x"])--Prints 11

All of the table can have different types of indexes to access value, and when a new entry is needed, the table automatically grows.

Copy Code code as follows:

A = {}
For i = 1
A[i] = i * 2
End
Print (a[9])
a["x"] = 10
Print (a["x"])
The variables in print (a["y"])--table, like global variables, are nil before they are assigned a value.

--The output result is
--18
--10
--nil

Another way to access values in a table is provided in Lua, as shown in the following example:

Copy Code code as follows:

a.x = 10--Equivalent to a["x"] = 10
Print (a.x)--equivalent to print (a["x"])
Print (A.Y)--equivalent to print (a["y"])

For LUA, the two approaches are equivalent. But for developers, the point of writing implicitly represents a table as a record, a structure in C language. The string notation previously described means that any string can be used as the key of the table.
If you need to represent a table as a traditional array, simply use an integer as the key to the table. Such as:
Copy Code code as follows:

A = {}
For i = 1,10 do
A[i] = i * 2
End

For i = 1,10 do
Print (A[i])
End


In Lua, I'm usually used to 1 as the starting value for an array index. And there are many internal mechanisms that depend on this practice. Such as:
Copy Code code as follows:

A = {}
For i = 1,10 do
A[i] = i * 2
End

For i = 1, #a do
Print (A[i])
End

Because the array is actually still a table, the calculation of the size of the array requires attention to some special scenes, such as:

Copy Code code as follows:

A = {}
A[1000] = 1

In the example above, the value of an element whose index value is 1--999 in array A is nil. Lua, in turn, nil the end of the data as a marker. When an array contains "voids", that is, the middle contains the nil value, the length operator # will assume that these nil elements are the end signs. Certainly this is not the result we want. So for these arrays that contain "voids," we can return the maximum positive index value of the table through the function Table.maxn (). Such as:
Copy Code code as follows:

A = {}
A[1000] = 1
Print (TABLE.MAXN (a))

--Output 1000

6. Function (functions):
In Lua, functions can be stored in variables, can pass other functions through parameters, and can be returned as values for other functions. This feature gives the language a great deal of flexibility.

    7. UserData (custom type):
    because the UserData type can store any C-language data in a LUA variable. In Lua, this type does not have much predefined operations and can only be assigned and tested for equality. UserData is used to represent a new type created by an application or a C language library.

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.