LUA Scripting language Basics

Source: Internet
Author: User
Tags lua

Comments

In Lua, you can use single-line comments and multiline comments.
In a single-line comment, a continuous two minus "--" indicates the beginning of the comment and continues until the end of the line. Equivalent to "//" in the C + + language.
In a multiline comment, the comment begins with "--[[" and continues until "]". This annotation is equivalent to "/*...*/" in the C language. In the comments, "[[" and "]]" can be nested.

Separator

In Lua, statements can be separated by semicolons ";" or by whitespace. In general, if multiple statements are written on the same line, the recommendations are always separated by semicolons.

Judgment and circulation

Condition control: If condition then ... elseif condition then ... else ... end
While loop: While condition do ... end
Repeat cycle: repeat ... until conditions
For loop: For variable = initial, end value, step do ... end
For loop: For variable 1, variable 2, ..., variable n in table or enumeration function do ... end

Note that the For loop variable always acts only on the for local variable, and you can omit the step value, at which point the For loop uses 1 as the stepping value.
You can use break to abort a loop.

Statement block


Statement blocks are enclosed in C + + with "{" and "}", in Lua, which is surrounded by do and end. Like what:
Do print ("Hello") end
You can set local variables in the function and in the statement block.

Assignment statements

The assignment statement was hardened in Lua. It can assign values to multiple variables at the same time.
For example:
a,b,c,d=1,2,3,4
Even the following:
A,b=b,a--What a convenient exchange variable function AH.
By default, variables are always considered global. If you want to define a local variable, you need to use the local description at the first time. Like what:
Local a,b,c = All-in-one-a,b,c are local variables

Numeric operations

Like the C language, support +,-, *, a also more "^". This represents an exponential exponentiation operation. For example 2^3 result is 8, 2^4 result is 16.
Connect two strings, you can use "..." The Transport Department symbol. Such as:
"This a" ... " String. "--equals" This a string "

Comparison operation

< > <= >= = = ~=
respectively, less than, greater than, not greater than, not less than, equal, unequal
All of these operators always return TRUE or false.
For table,function and UserData types of data, only = = and. Equality means that two variables refer to the same data. Like what:
a={1,2}
B=a
Print (A==b, a~=b)--True, False
a={1,2}
b={1,2}
Print (A==b, a~=b)--False, True

Logical operations

And, or, not
Among them, and and OR and the C language is particularly different.
Here, remember that in Lua, only false and nil are counted as false, and anything else counted as true,0 is also true!
The operation result of and and or is not true and false, but is related to its two operands.
A and B: If A is false, A is returned, or B is returned
A or B: If A is true, A is returned, or B is returned

For a few examples:
Print (4 and 5)--5
Print (nil and all)--nil
Print (false and a)---false
Print (4 or 5)-4
Print (False or 5)-5

This is a very useful feature in Lua, and it is also a more confusing Wei feature.
We can simulate the statement in C: x = a? B:c, in Lua, can be written as: X B or C.
The most useful statement is: x = x or V, which is equivalent to: if not x and then x = V end.

. Operator precedence, from high to low, in the following order:
^
Not-(unary operation)
* /
+ -
.. (String connection)
< > <= >= ~= = =
and
Or

Reference: http://job.17173.com/content/2009-01-22/20090122143452606,1.shtml

Variable type

How do you determine what type of a variable is? You can use the type () function to check. There are several types of LUA support:

Nil null value, all unused variables, are nil. Nil is both a value and a type.
Boolean Boolean value
Number value, in Lua, the value is equal to the C language double
String string that, if you wish, can contain the ' \ S ' character.
Table relational table type, this type of function is more powerful.
function type, do not doubt that functions are also a type, that is, all functions, which are itself a variable.
Userdata Well, this type is specifically designed to deal with Lua's hosts. Hosts are usually written in C and C + +, in which case the UserData can be any data type of the host, often with structs and pointers.
Thread type, there is no real thread in Lua. You can run a function into several parts in Lua. If you're interested, take a look at the LUA documentation.

Definition of a variable

In all languages, variables are used. In Lua, no matter where you use variables, you don't need to declare them, and all of these variables are always global, unless you precede them with "local."
Pay particular attention to this, because you might want to use local variables in the function, but forget to use local to illustrate them.
As for the variable name, it is case-sensitive. In other words, a and a are two different variables.
The way to define a variable is to assign a value. The "=" operation is used to assign values to the
Let's define several common types of variables together.

A. Nil
As previously mentioned, the value of a variable that has not been used is nil. Sometimes we also need to clear a variable, and we can assign a nil value to the variable directly. Such as:
Var1=nil--Please note that nil must be lowercase

B. Boolean
A Boolean value is usually used when a condition is judged. There are two types of Boolean values: True and False. In Lua, only false and nil are evaluated to false, and all other types of values are true. such as 0, empty string and so on, are true. Don't be misled by the habit of C, 0 is indeed true in Lua. You can also assign a Boolean value directly to a variable, such as:
Varboolean = True

C. Number
In Lua, there is no integer type and no need. In general, rounding errors are not generated as long as the values are not very large (for example, no more than 100,000,000,000,000). On many CPUs, the arithmetic of real numbers is not slower than integers.
The representation of a real number is similar to the C language, such as:
4 0.4 4.57e-3 0.3e12 5e+20

D. String
String, which is always a very common type of advanced. In Lua, you can easily define very long, long strings.
There are several ways in which strings are represented in Lua, and the most common method is to enclose a string in double or single quotation marks, such as:
"This is a string."
As with the C language, it supports some escape characters, which are listed below:
\a Bell
\b Back Space
\f Form Feed
\ NewLine
\ r Carriage Return
\ t Horizontal tab
\v Vertical Tab
\ Backslash
\ "Double Quote
\ ' Single quote
\[Left Square Bracket
\] Right Square bracket

Since this string can only be written on one line, it is unavoidable to use the escape character. Added a string of escape characters, it seems to be really not flattering, such as:
"One Line\nnext line\n\" in Quotes\ ", ' in quotes '"
A whole bunch of "\" signs make people look like a turnoff. If you feel the same way with me, then, in Lua, we can use a different notation: "[[" and "]]" to enclose multiple lines of string, such as:
page = [[
<HTML>
<HEAD>
<title>an HTML page</title>
</HEAD>
<BODY>
<a href= "http://www.lua.org" >Lua</A>
[[a text between double brackets]]
</BODY>
</HTML>
]]

It is important to note that in such a string, "\[" or "\" should still be used to avoid ambiguity if the "[[" or "]]" is contained in a separate use. Of course, this is rarely the case.

Table


Relational table type, which is a very powerful type. We can think of this type as an array. Just an array of C, which can only be indexed with a positive integer; in Lua, you can use any type to count the index of a group, except nil. Similarly, in C, the contents of an array allow only one type; in Lua, you can also use any type of value to count the contents of a group except nil.

The definition of table is simple, and its main feature is to enclose a series of data elements with "{" and "}". Than

T1 = {}--Define an empty table
T1[1]=10--and then we can use it just like the C language.
t1["John"]={age=27, gender= "Male"}
This sentence is equivalent to:
t1["John"]={}--Define a table first, remember the undefined variable is the nil type?
t1["John" ["Age"]=27
t1["John" ["Gender"]= "Male"
When the index of a table is a string, we can simply write:
T1. john={}
T1. John.age=27
T1. John.gender= "Male"
Or
T1. john{age=27, gender= "Male"}
This is a very strong feature.

When defining a table, we can write all of the data together in between "{" and "}", which is very convenient and nice to look at. For example, the previous definition of T1, we can write:

t1=
{
10,--equivalent to [1] = 10
[100] = 40,
John=-If you're willing, you can write: ["John"] =
{
age=27,--If you should, you can also write: ["Age"] =27
Gender=male-If you would, you can also write: ["Gender"] le
},
20--equivalent to [2] = 20
}

It looks beautiful, doesn't it? When we write, we need to pay attention to three points:
First, all elements are always separated by commas ",";
Second, all index values need to be "[" and "], and if it is a string, you can also remove the quotation marks and brackets;
Thirdly, if the index is not written, the index is considered to be a number, and is automatically compiled from 1 sequentially;

The construction of table types is so convenient that they are often used instead of configuration files. Yes, no doubt, it is more beautiful than INI file, and much more powerful.

Function


function, in Lua, the definition of a function is simple. The typical definition is as follows:
Functions Add (A, B)--add is the function name, and a is the name of the parameter
Return A+b-Return returns the result of running the function
End

Please note that the return language must be written before end.
A function is also a variable type, and the function definition above is actually equivalent to:
Add = function (A, b) return a+b end
When you re-assign a value to add, it no longer represents the function. You can even assign the add arbitrary data, including nil (so that you clear the Add variable). is function very much like a C-language functional pointer?

Like the C language, Lua's functions can accept a variable number of parameters, which are also defined by "...", such as:
function sum (A, B,...)
If you want to get ... Represents the parameter that can be obtained by accessing the ARG local variable (table type) in the function.
such as SUM (1,2,3,4)
Then, in the function, a = 1, b = 2, arg = {3, 4}
More valuable is that it can return multiple results at the same time, such as:
function S ()
Return 1,2,3,4
End
A,b,c,d = S ()-At this point, a = 1, b = 2, c = 3, d = 4
As I said earlier, table types can have any type of value, including functions! So, there is a very powerful feature is the table with the function, oh, I think more appropriate should be said to be the object bar. Lua can use object-oriented programming. Don't believe me? Let me give you the following examples:

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, T.add (t,10) sentence is a bit of dirt, right? It doesn't matter, in Lua, you can write in simple:
T:add (10)--equivalent to T.add (t,10)

Reference: http://job.17173.com/content/2009-01-22/20090122143452606,3.shtml

LUA Scripting language Basics

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.