Lua Programming Basics

Source: Internet
Author: User

--Suggest using notepad++ to open the language to LUA


In Lua, everything is a variable, except for keywords. Please remember this sentence.


I. First is the comment


Writing a program is always a comment.
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.


II. Lua programming


The classic "Hello World" program is always used to start introducing a language. In Lua, it's simple to write a program like this:
Print ("Hello World")
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.
Lua has several program control statements, such as:


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.
If you have the basics of programming, like you've learned basic,c or something, you'll find Lua easy. But there are several areas of LUA that are obviously different from these programming languages, so please pay special attention.


. 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 when you first assign the value. Like what:
Local a,b,c = All-in-one-a,b,c are local variables


. Numeric operations
Like the C language, support +,-, *,/. But Lua has one 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 ~= can be used. 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 only false and nil are counted as false in Lua, and any other data is computed 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 = A and 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
Iii. keywords


The keyword cannot be a variable. LUA does not have many 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 types


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, we say slowly in the back.
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.


V. Definition of variables


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.
E. 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 "}". Like what:


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"]={}--must first be defined as a table, remember that undefined variable is 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 intended, you can also write: ["Gender"] =male
},
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 enclosed in "[" and "]", and in the case of strings, 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.


F. 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. If you have to put a return in the middle, write it: do return end.
Remember that the function is also a variable type, as I said earlier? 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


But T.add (t,10) is a bit of dirt, isn't it? It doesn't matter, in Lua, you can write in simple:
T:add (10)--equivalent to T.add (t,10)


G. Userdata and Thread
These two types of topics, beyond the content of this article, it is not intended to elaborate.
Vi. concluding remarks


Is this the end of it? Of course not, next, you need to use the LUA interpreter to help you understand and practice. This article just helps you get a general idea of Lua's syntax. If you have a programming base, you will soon be getting started with Lua.
Like the C language, LUA provides quite a number of standard functions to enhance the functionality of the language. With these standard functions, you can easily manipulate various data types and process input and output. For this information, you can refer to "Programming in Lua" book, you can watch the electronic version directly on the network, the URL is: http://www.lua.org/pil/index.html
Of course, the most powerful feature of LUA is its ability to work closely with the host program, so in the next article, I'll show you how to use the Lua language as a script in your program to interact with your program and LUA scripts.


Use process


1. Use of functions


The following procedure demonstrates how to use functions in Lua, and local variables
Example E02.lua
--Functions
function Pythagorean (A, B)
Local C2 = a^2 + b^2
return sqrt (C2)
End
Print (Pythagorean (3,4))


Run results
5


Program Description
In Lua, the function is defined in the following format:
Function name (parameter)
...
End
Unlike the Pascal language, end does not need to be paired with begin, but only after the end of the function. The function of this example is known right triangle right angle edge, the length of the hypotenuse. The parameter, a, and B respectively indicate the right side length
A local variable is defined within the function to store the square of the hypotenuse. As with the C language, code defined within a function is not executed directly, but only when the main program is called.
Local means that a local variable is defined, and if no local is represented as a global variable, the scope of local is between the innermost end and its paired keywords, such as if ... end, while ... end, and so on. C2. The scope of a global variable is the entire program.


2. Looping statements


Example E03.lua
--Loops
For i=1,5 do
Print ("I am Now": I
End


Run results
I am now 1
I am now 2
I am now 3
I am now 4
I am now 5


Program Description
Here we use the For statement.
For variable = parameter 1, parameter 2, parameter 3 do
Loop body
End
The variable will be step by parameter 3, change from parameter 1 to parameter 2
For example:
For i=1,f (x) do print (i) end
For i=10,1,-1 do print (i) end


Print here ("I am Now"). i), we used: This is used to connect two strings, even in (1) Try to mention, I do not know that you are correct. Although I is an integral type here, LUA automatically turns into a string type when it is processed, and does not need to be bothered.


3. Conditional branching statements


Example E04.lua
--Loops and conditionals
For i=1,5 do
Print ("I am Now": I
If I < 2 Then
Print ("small")
ElseIf I < 4 then
Print ("Medium")
Else
Print ("Big")
End
End


Run results
I am now 1
Small
I am now 2
Medium
I am now 3
Medium
I am now 4
Big
I am now 5
Big


Program Description
The If else usage is simpler, similar to the C language, but it is important to note that the entire if requires only an end, even if multiple ElseIf are used, and an end.
For example
If op = = "+" Then
R = A + b
ElseIf op = = "-" Then
r = A-B
ElseIf op = = "*" Then
r = A*b
ElseIf op = = "/" Then
R = A/b
Else
Error ("Invalid operation")
End




4. Try It


In addition to the For Loop, LUA supports a variety of loops, using while...do and Repeat...until to overwrite the for program in this article.
Use of arrays


1. Introduction


The LUA language has only one basic data structure, that is, table, all other data structures such as arrays, classes, can be implemented by table.


Subscript for 2.table


Example E05.lua
--Arrays
MyData = {}
Mydata[0] = "foo"
MYDATA[1] = 42


--Hash Tables
mydata["Bar"] = "baz"


--Iterate through the
--Structure
For key, value in MyData do
Print (key.. "=": Value
End


Output results
0=foo
1=42
Bar=baz


Program Description
A table mydata={} is defined first, and then the number is assigned two values as a subscript. This definition method is similar to the array in C, but unlike arrays, each array element does not need to be of the same type, as in this case one is an integer and one is a string.


In the second part of the program, a string is subscript, and an element is added to the table. This table is very much like the map inside the STL. Table subscripts can be any of the basic types that LUA supports, except for nil values.


Lua's handling of table-occupied memory is automatic, as in the following code
A = {}
a["x"] = 10
b = A--' B ' refers to the same table as ' a '
Print (b["x"])--10
b["x"] = 20
Print (a["x"])--20
A = nil-now only ' B ' still refers to the table
b = Nil--now there is no references left to the table
B and a both point to the same table, occupy only one piece of memory, and when executed to a = nil, B still points to table,
When executing to B=nil, because there is no variable pointing to table, Lua automatically frees the memory occupied by table


Nesting of 3.Table


The use of table can also be nested, as in the following example
Example E06.lua
--Table ' constructor '
MyPolygon = {
Color= "Blue",
thickness=2,
npoints=4;
{x=0, y=0},
{x=-10, y=0},
{x=-5, y=4},
{x=0, y=4}
}


--Print The color
Print (mypolygon["color"])


--Print it again using dot
--notation
Print (Mypolygon.color)


--the points is accessible
-in mypolygon[1] to mypolygon[4]


--Print The second point ' s X
--coordinate
Print (mypolygon[2].x)


Program Description


First create a table, unlike the previous example, there is {x=0,y=0} in the table's constructor, what does that mean? This is actually a small table, defined in the large table, the table name of the small table is omitted. The last line of mypolygon[2].x is the access way of the small table inside the big table.




Lua Programming 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.