Lua quick start tutorial

Source: Internet
Author: User

Lua script syntax description (revision)
Lua script syntax description (add some features of lua5.1)
Lua's syntax is relatively simple and easier to learn, but its functions are not weak.
Therefore, I will simply sum up some of Lua's syntax rules for easy query. After reading it, you will know how to write the Lua program.
In Lua, everything is a variable except a keyword.
I. annotation first
Writing a program is always without comments.
In Lua, you can use single-line and multi-line annotations.
In a single line comment, two consecutive minus signs "--" indicate the start of the comment until the end of the line. It is equivalent to "//" in C ++ "//".
In multi-line comments, the Comment starts from "-- [" and continues. This annotation is equivalent to "/*... */" in C language "/*...*/". In the annotations, "[[" and "]" can be nested (in lua5.1, a number of "=" signs can be added in the brackets, for example, [= [...] =]), see the following string description.

Ii. Lua Programming
A classic "Hello World" program is always used to introduce a language. In Lua, writing such a program is simple:
Print ("Hello World ")
In Lua, statements can be separated by semicolons (;) or blank spaces. Generally, if multiple statements are written in the same row, we recommend that you use semicolons to separate them.
Lua has several program control statements, such:
Example of control statement format
If if condition then... elseif condition then... else... end if 1 + 1 = 2 then print ("true ")
Elseif 1 + 2 ~ = 3 then print ("true ")
Else print ("false") End

While while condition do... end while 1 + 1 ~ = 2 do print ("true") End

Repeat repeat... Until condition repeat print ("hello") until 1 + 1 ~ = 2

For for variable = initial value, end value, step do... end for I = 1, 10, 2 do print (I) End

For variable 1, variable 2,... Variable N in table or enumeration function do... end for a, B in mylist do print (a, B) End

Note that the For Loop Variable always acts only on the partial variable of the for. When the step value is omitted, 1 is used as the step value for the for loop.
Break can be used to abort a loop.
Compared with the C language, Lua is obviously different in several aspects, so pay special attention to the following points:

. Statement Block
The statement block is enclosed by "{" and "}" in C. In Lua, It is enclosed by do and end. For example:
Do print ("hello") End
You can set local variables in functions and statement blocks.

. Assignment Statement
The value assignment statement is enhanced in Lua. It can assign values to multiple variables at the same time.
For example:
A, B, c, d = 1, 2, 3, 4
A, B = B, a -- how convenient the variable exchange function is.
By default, variables are always considered global. If you need to define a local variable, you need to use local to describe it during the first assignment. For example:
Local a, B, c = 1, 2, 3 -- A, B, C are local variables

. Numeric operation
Like the C language, it supports + ,-,*,/. But Lua has another "^ ". This indicates exponential multiplication. For example, the result of 2 ^ 3 is 8, and the result of 2 ^ 4 is 16.
Connect two strings. You can use the ".." operator. For example:
"This a"... "string." -- equal to "this a string"

. Comparison operation
Comparison symbol <><=>== ~ =
Meaning less than or equal to greater than or equal to equal not equal

All these operators always return true or false.
For Table, function, and userdata data, only = and ~ = Available. The two variables reference the same data. For example:
A = {1, 2}
B =
Print (A = B, ~ = B) -- Output True, false
A = {1, 2}
B = {1, 2}
Print (A = B, ~ = B) -- outputs false, true
. Logical operation
And, or, not
And or differ significantly from C.
Here, remember that in Lua, only false and nil are calculated as false, and any other data is calculated as true, and 0 is also true!
The operation result of and or is not true or false, but related to its two operands.
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) -- output 5
Print (nil and 13) -- output Nil
Print (false and 13) -- output false
Print (4 or 5) -- output 4
Print (false or 5) -- output 5

This is a very useful feature in Lua, and it is also a hybrid feature.
We can simulate the C language statement: x =? B: C. In Lua, it can be written as: x = A and B or C.
The most useful statement is: x = X or V, which is equivalent to: If not X then x = V end.

. Operator priority. The order from low to high is as follows:
<> <=> = ~ ===
.. (String connection)
Not #(lua5.1 length fetch operation)-(mona1 Operation)
Like C, parentheses can change the priority.

Iii. Keywords
Keywords cannot be used as variables. There are not many Lua keywords, just the following:

And break do else elseif
End false for function if
In local nil not or
Repeat return then true until while

Iv. Variable type
How can we determine the type of a variable? You can use the type () function to check. Lua supports the following types:
Nil null. All unused variables are nil. Nil is both a value and a type.
Boolean value. There are only two valid values: true and false.
Number value. In Lua, the value is equivalent to double in C.
String string. If you want to, the string can contain "/0" characters (this is different from the C language that always ends with "/0)
Table relational table type. This type has powerful functions. For more information, see the following section.
Function type. Do not doubt that a function is also a type. That is to say, all functions are a variable.
Userdata: Well, this type is used to deal with Lua's host. Generally, the host is written in C and C ++. In this case, userdata can be any data type of the host, usually including struct and pointer.
Thread thread type. There is no real thread in Lua. In Lua, a function can be divided into several parts for running. If you are interested, you can go to Lua's documents.
Now let's look back at it. I don't think it's a thread type. Instead, the iterator function is used for traversal.
For example:
Function range (N)
Local I = 0
While (I <n) Do
Coroutine. Yield (I)
I = I + 1
Unfortunately, you need the coroutine. Resume function to continue running. Please advise.

V. variable definition
Variables are used in all languages. In Lua, no variables need to be declared wherever they are used, and all these variables are always global variables unless we add "local" before ". Pay special attention to this, because we may want to use local variables in the function, but forget to use local to describe.
Variable names are case-sensitive. That is to say, a and a are two different variables.
To define a variable, assign a value. "=" Operations are used to assign values.
Let's define several common types of variables.
  A. Nil
As mentioned above, the values of unused variables are all nil. Sometimes we also need to clear a variable. At this time, we can directly assign the variable a nil value. For example:
Var1 = Nil -- note that nil must be in lowercase.

  B. Boolean
Boolean values are usually used for condition determination. There are two types of Boolean values: true and false. In Lua, only false and nil are calculated as false, and all other types of values are true. For example, 0 and null strings are all true. Do not be misled by the C language habits. 0 is true in Lua. You can also assign a Boolean value to a variable, for example:
Theboolean = true

  C. Number
In Lua, there is no integer type and it is not required. Generally, as long as the value is not very large (for example, it cannot exceed 100,000,000,000,000), there will be no rounding error. In today's mainstream PCs where Windows XP can run, real number operations are not slower than integers.
The representation of real numbers, similar to the C language, for example:
4 0.4 4.57e-3 0.3e12 5E + 20

  D. String
String is always a very common advanced type. In Lua, we can easily define long and long strings.
There are several methods to represent a string in Lua. The most common method is to enclose a string with double quotation marks or single quotation marks, for example:
"That's go! "
'Hello world! '

Similar to the C language, it supports some escape characters. The list is as follows:
/A bell
/B back space
/F form feed
/N newline
/R carriage return
/T horizontal Tab
/V vertical Tab
// Backslash
/"Double quote
/"Single quote
/[Left square bracket
/] Right square bracket

Because such a string can only be written in one row, it is inevitable to use escape characters. It seems that the strings with escape characters are not flattering, for example:
"One Line/nnext line/n/" in quotes/"," in quotes ""
A lot of "/" symbols make people look quite appetizing. If you share the same feelings with me, we can use another Representation Method in Lua: Enclose strings of multiple rows with "[[" and. (Lua5.1: Several "=" signs can be added to the brackets, for example, [= [...] =]. For details, see the following example)
Example: The following statement indicates the exact same string:
A = 'alo/n123 "'
A = "Alo/n123 /""
A = '/97lo/10/04923 "'
A = [[AlO
123 "]
A = [= [
123 "] =]

It is worth noting that if this string contains a separate "[[" or "]", "/[" or "/]" is still used to avoid ambiguity. Of course, this situation rarely happens.

  E. Table
Relational table type, which is a very powerful type. We can regard this type as an array. Only arrays in C language can be indexed using positive integers. In Lua, You Can index arrays of any type, except nil. Similarly, in C language, the array content can only be one type. In Lua, you can also use any type of value as the array content, except nil.
The definition of table is very simple. Its main feature is to use "{" and "}" to enclose a series of data elements. For example:
T1 ={} -- Define an empty table
T1 [1] = 10 -- then we can use it like the C language.

T1 ["John"] = {age = 27, Gender = "male "}
This sentence is equivalent:
T1 ["John"] ={} -- must be defined as a table first. Do you still remember that the undefined variable is of the NIL type?
T1 ["John"] ["Age"] = 27
T1 ["John"] ["gender"] = "male"
When the index of a table is a string, it can be abbreviated:
T1.john = {}
T1.john. Age = 27
T1.john. Gender = "male"
T1.john {age = 27, Gender = "male "}
This is a strong feature.

When defining a table, we can write all the data content between "{" and "}". This is very convenient and nice-looking. For example, the previous T1 definition can be written as follows:
T1 =
10, -- equivalent to [1] = 10
[100] = 40,
John = -- If you intend, you can also write it as: ["John"] =
Age = 27, -- If you intend, you can also write it as: ["Age"] = 27
Gender = male -- if you are interested, you can also write it as: ["gender"] = male
20 -- equivalent to [2] = 20

It looks pretty, isn't it? Note the following three points when writing:
First, all elements are separated by commas;
Second, all index values must be enclosed by "[" and "]". If it is a string, you can also remove the quotation marks and brackets;
Third, if no index is written, the index will be regarded as a number and will be automatically edited from 1 in order;

The construction of table types is so convenient that they are often used instead of configuration files. Yes, you don't have to worry about it. It is more beautiful and powerful than the INI file.

 F. Function
Function. In Lua, the function definition is also very simple. A typical definition is as follows:
Function add (a, B) -- add is the function name, And A and B are the parameter names.
Return a + B -- return is used to return the function running result.

Note that the return language must be written before the end. If we have to put a return statement in the middle, we should write it as do return end.
Do you remember that the function is also a variable type? The above function definition is actually equivalent:
Add = function (a, B) return a + B End
When you assign a value to add again, it no longer indicates this function. We can even assign add arbitrary data, including nil (in this way, assign the value to nil, which will clear the variable ). Is a function like a function pointer in C?

Like C, Lua functions can accept the number of variable parameters, which are also defined by "...", for example:
Function sum (a, B ,)
If you want to obtain... you can access the ARG local variable (Table type) in the function to obtain the parameter (lua5.1: Remove Arg, and directly use "... "To represent variable parameters, the essence is Arg ).
Such as sum (1, 2, 3, 4)
Then, in the function, a = 1, B = 2, Arg = {3, 4} (lua5.1: a = 1, B = 2 ,... = {3, 4 })
More importantly, it can return multiple results at the same time, for example:
Function S ()
Return 1, 2, 3, 4
A, B, c, d = S () -- at this time, a = 1, B = 2, c = 3, D = 4

As mentioned above, the table type can have any type of values, including functions! Therefore, a very powerful feature is that tables with functions, oh, I think it should be more appropriate to say that it is an object. Lua can use object-oriented programming. Believe it? Example:
T =
Age = 27
Add = function (self, n) self. Age = self. Age + N end
Print (T. Age) -- 27
T. Add (T, 10)
Print (T. Age) -- 37

However, the sentence T. Add (T, 10) is a bit earthy, right? It doesn't matter. In Lua, We Can abbreviated it:
T: add (10) -- equivalent to T. Add (T, 10)

  G. userdata and thread
These two types of topics are beyond the content of this article and will not be discussed in detail.

Vi. Concluding remarks
Is that the end? Of course not. Next, we need to use the Lua interpreter to help understand and practice. I believe this will get started with Lua faster.
Like the C language, Lua provides a considerable number of standard functions to enhance language functions. Using these standard functions, you can easily operate various data types and process input and output. For this information, we can refer to the book programming in Lua, you can also directly watch the electronic version on the network, the URL is:
Note: Part of this article is extracted and translated from the Lua random document.
Related links:
1. Lua Official Website:
2. Lua wiki website, where you can find a lot of related materials such as documents, tutorials, extensions, and C/C ++ packaging:

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.