Lua Easy Start Tutorial

Source: Internet
Author: User

Environment: Lua for Windows (LfW)
Home: http://luaforwindows.luaforge.net/
https://code.google.com/p/luaforwindows/

Lua for Windows is actually a set of LUA development environments that include:
LUA interpreter (LUA interpreter)
Lua Reference Manual (LUA reference manual)
Quick Lua Tour (LUA QuickStart)
Examples (LUA Paradigm)
Libraries with documentation (some LUA libraries and documentation)
SciTE (a great multi-purpose editor, has already made special settings for LUA)

Lua Scripting Syntax Description (revision)
LUA Scripting Syntax Description (add lua5.1 partial features)
Lua's syntax is relatively simple, learning is also relatively labor-saving, but the function is not weak.
So, I simply summed up some of the LUA grammar rules, easy to use to check it. After reading it, I know how to write the LUA program.
In Lua, everything is a variable, except for keywords.
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 (in lua5.1, the middle bracket can be added several "=" number, such as [==[...] = =]), see the following string representation description.

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:
Control Statement Format Example
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 and 1+1~=2 do print ("true") end

Repeat Repeat until conditions Repeat print ("Hello") until 1+1~=2

For-for-variable = initial, end value, step do ... end for i = 1, 2 do print (i) end

For-for-variable 1, variable 2, ... Variable n in table or enumeration function do ... end for A, b in MyList do print (A, c) end


Note that the For loop variable always acts only on the for local variable, and when the step value is omitted, the For loop uses 1 as the stepping value.
Using break can be used to abort a loop.
In contrast to the C language, there are several areas where Lua is distinctly different, so pay special attention to it:

. 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 need 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
Compare symbols < > <= >= = = ~=
meaning less than or equal to or greater than or equal to equality

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)-Output true, False
a={1,2}
b={1,2}
Print (A==b, a~=b)-Output 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)--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 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 low to high order, is as follows:
Or
and
< > <= >= ~= = =
.. (String connection)
+     -
*     /     %
Not # (lua5.1 take length operation)-(unary operation)
^
Like the C language, parentheses can change precedence.

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.
A Boolean Boolean value that has only two valid values: True and False
Number value, in Lua, the value is equal to the C language double
String string that, if you wish, can contain the character "s" (which is not the same as the C language always ends with "\")
Table relational table type, this type of function is more powerful, please refer to the following.
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.
Now look back and think it's not a thread type. It seems to be used to do the traversal, like the iterator function.
Such as:
function range (n)
Local i = 0
while (I < n) do
Coroutine.yield (i)
i = i + 1
End
End
Unfortunately is to continue to run, need coroutine.resume function, a little chicken. Please advise.

v. Definition of variables
In all languages, variables are used. In Lua, no matter where the variable is used, no declaration is required, and all of these variables are always global, unless we precede them with "local". This is especially important because we 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:
Theboolean = 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). In today's mainstream PC, where windowsxp can run, the arithmetic of real numbers is no 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, we can define very long, long strings very conveniently.
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:
"That ' s go!"
Or
' Hello world! '

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. (lua5.1: A number of "=" numbers can be added to the middle bracket, such as [==[...] = =], see example below)
Example: The following statement represents the exact same string:
A = ' alo\n123 '
A = "alo\n123\" "
A = ' \97lo\10\04923 '
A = [[Alo
123 "]
A = [==[
Alo
123 "]==]

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 we have to put a return in the middle, then we should write: 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. We can even assign the add arbitrary data, including nil (so that the assignment is nil, the variable will be cleared). 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 ... The parameter that is represented can be accessed in the function by the ARG local variable (table type) obtained (lua5.1: cancels Arg, and directly uses "..." to represent the variable parameter, which is essentially 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 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? Examples are as follows:
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, we can simply write:
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. Syntax

A. Closures
Example One

function Newcounter ()    Local i = 0    return function ()     --anonymous function       i = i + 1        return i    enden D c1 = Newcounter () print (C1 ())-  1print (C1 ())-  2

Example two:

function Mypower (x)    return function (y) return y^x endend power2 = Mypower (2) Power3 = Mypower (3) Print (Power2 (4))--4 2 --5 (Power3 (5)) 3-time-square

B. Loading

We can load other LUA files directly using require ("Model_name"), with the suffix of. Lua. The file is executed directly at the time of loading. Like what:
We have a Hello.lua file:

Print ("Hello, world!")

If we: Require ("Hello"), then directly output Hello, world! The
Attention:
1) require function, when loading the same LUA file, only the first time will be executed, the same after the same is not executed.
2) If you want each file to be executed, you can use the Dofile ("Hello") function
3) If you want to play after loading and do not execute when you need to execute, you can use the LoadFile () function as follows:

Local Hello = loadfile ("Hello") .... Hello ()

LoadFile ("Hello") after the file is not executed, we assign the file to a variable hello, when hello () is actually executed. (We'd like JavaScript to have the same function.)
Of course, the more standard gameplay is shown below.
Suppose we have a file called Mymod.lua, which reads as follows:
File name: Mymod.lua

Local Haosmodel = {} local function getname ()    return "Hao Chen" End Function haosmodel.greeting ()    print ("Hello, My Name is ". GetName ()) End return Haosmodel

So we can use this:

Local Hao_model = require ("Mymod") Hao_model. Greeting ()

In fact, require do the following: (so you know why our module files are written like that)

Local Hao_model = (function ()  --mymod.lua file content--end) ()


Vi. concluding remarks
Is this the end of it? Of course not, next, we need to use the LUA interpreter to help understand and practice. Believe that this will be faster for LUA to get started.
Like the C language, LUA provides quite a number of standard functions to enhance the functionality of the language. Using these standard functions, it is convenient to manipulate various data types and handle input and output. For this information, we can refer to "Programming in Lua" book, you can also directly watch the electronic version on the network, the address is: http://www.lua.org/pil/index.html
  
Note: Some of the contents of this article are summarized and translated from Lua random documents.
RELATED links:
1. Lua Official website: http://www.lua.org
2. The Lua wiki site, where you can find a lot of relevant information, such as documentation, tutorials, extensions, and packaging for C + +: http://lua-users.org/wiki/

Lua Easy Start tutorial

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.