Lua game script language getting started

Source: Internet
Author: User

Lua gamesScriptLanguageThis document describes how to get started.LuaProgram Design. I suppose everyone has learned at least one programming.LanguageSuch as Basic or C, especially C. BecauseLuaIs used as a script in the Host Program.

LuaThe syntax is relatively simple and easier to learn, but the function is not weak. InLuaAll are variables except keywords. Remember this sentence.

1. First, comment

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, "[[" indicates that the comments start and continue. This annotation is equivalent "/*... */". In comments, "[[" and "]" can be nested.

2. Lua Programming

A classic "Hello world" program is always used to introduce a language. In Lua, writing such a program is simple:

 
 
  1. 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:

Conditional Control: if condition then... Elseif condition then... Else... End

While loop: while condition do... End

Repeat loop: repeat... Until Condition

For Loop: for variable = initial value, 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 partial variable of the for, you can also omit the step value, at this time, the for Loop will use 1 as the step value. You can use break to stop a loop. If you have the foundation of programming, such as Basic and C, you will feel that Lua is not difficult. However, Lua has several differences from these programming languages, so pay special attention to them.

. Statement Block

The statement block is enclosed by "{" and "}" in C ++. In Lua, It is enclosed by do and end. For example:

 
 
  1. 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:

 
 
  1. a,b,c,d=1,2,3,4 

Even:

A, B = B, a how convenient it is to exchange variables.

By default, variables are always considered global. If you want to define a local variable, you must use local to describe it during the first assignment. For example:

 
 
  1. 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:

 
 
  1. "This a"... "string." equals "this a string"

. Comparison operation

 
 
  1. < > <= >= == ~= 

They indicate less than, greater than, not greater than, not less than, 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:

 
 
  1. a={1,2}  
  2. b=a 
  3. print(a==b, a~=b) true, false  
  4. a={1,2}  
  5. b={1,2}  
  6. print(a==b, a~=b) false, true 

. Logical operation

 
 
  1. and, or, not 

Where, and or and CLanguageThe difference is very big.

Here, remember thatLuaIn, 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:

 
 
  1. print(4 and 5) > 5  
  2. print(nil and 13) > nil  
  3. print(false and 13) > false  
  4. print(4 or 5) > 4  
  5. print(false or 5) > 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 high to low is as follows:

 
 
  1. ^
  2. Not-mona1 Operation)
  3. */
  4. +-
  5. .. String connection)
  6. <> <=> = ~ ===
  7. And
  8. Or

3. Keywords

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

 
 
  1. and break do else elseif  
  2. end false for function if  
  3. in local nil not or  
  4. repeat return then true until while 

4. 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

Number value. In Lua, the value is equivalent to double in C.

String. If you want to, the String can contain '\ 0' characters.

Table relational Table type, which has powerful functions. Let's talk about it later.

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

5. variable definition

Variables are used in all languages. In Lua, no matter where you use variables, you do not need to declare them, and all these variables are always global variables unless you add "local" in front ". Pay special attention to this, because you 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 together.

1) 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 please note that nil must be in lower case

2) 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:

 
 
  1. varboolean = true 

3) Number

In Lua, there is no integer type and it is not required. Generally, as long as the value is not very large, such as not greater than 100,000,000,000,000), there will be no rounding error. In many CPUs, real number operations are not slower than integers.

The representation of real numbers, similar to the C language, for example:

 
 
  1. 4 0.4 4.57e-3 0.3e12 5e+20 

4) String

String is always a very common advanced type. In Lua, you 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:

 
 
  1. "This is a string." 

Similar to the C language, it supports some escape characters. The list is as follows:

 
 
  1. \a bell  
  2. \b back space  
  3. \f form feed  
  4. \n newline  
  5. \r carriage return  
  6. \t horizontal tab  
  7. \v vertical tab  
  8. \\ backslash  
  9. \" double quote  
  10. \' single quote  
  11. \[ left square bracket  
  12. \] 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:

 
 
  1. "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, for example:

 
 
  1. page = [[  
  2. <HTML> 
  3. <HEAD> 
  4. <TITLE>An HTML Page</TITLE> 
  5. </HEAD> 
  6. <BODY> 
  7. <A HREF="http://www.lua.org">Lua</A> 
  8. [[a text between double brackets]]  
  9. </BODY> 
  10. </HTML> 
  11. ]] 

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.

5) Table

Relational table type, which is a very powerful type. We can regard this type as an array. Only an array in C language can be indexed using positive integers.Lua, You can use any type for array indexing, except nil. SimilarlyLanguageInLua, You can also use any type of value as the content of the array, 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:

 
 
  1. T1 ={} defines an empty table
  2. T1 [1] = 10 then we can use it like the C language.
  3. T1 ["John"] = {Age = 27, Gender = "Male "}

This sentence is equivalent:

 
 
  1. T1 ["John"] ={} must be defined as a table first. Do you still remember that the undefined variable is of the nil type?
  2. T1 ["John"] ["Age"] = 27
  3. T1 ["John"] ["Gender"] = "Male"

When the index of a table is a string, it can be abbreviated:

 
 
  1. T1.John = {}
  2. T1.John. Age = 27
  3. T1.John. Gender = "Male"
  4. Or
  5. 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:

 
 
  1. T1 =
  2. {
  3. 10, equivalent to [1] = 10
  4. [100] = 40,
  5. John = if your original intention is true, you can also write it as: ["John"] =
  6. {
  7. Age = 27. If you want to write it as follows: ["Age"] = 27
  8. Gender = Male you can also write it as: ["Gender"] = Male
  9. },
  10. 20 is equivalent to [2] = 20
  11. }

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.

6) Function

Function. In Lua, the function definition is also very simple. A typical definition is as follows:

 
 
  1. Function add (a, B) add is the function name, And a and B are the parameter names.
  2. Return a + B return is used to return the function running result.
  3. End

Note that the return language must be written before the end. If you have to put a return statement in the middle, write it as do return end.

Do you remember that the function is also a variable type? The above function definition is actually equivalent:

 
 
  1. add = function (a,b) return a+b end 

When you assign a value to add again, it no longer indicates this function. You can even assign add arbitrary data, including nil, so that you can clear the add variable ). Is a Function like a Function pointer in C? Like the C language, Lua functions can accept the number of variable parameters. It also uses "... "To define, such:

 
 
  1. function sum (a,b,…) 

If you want to obtain... Parameters, you can access the arg local variable table type in the function.

 
 
  1. Such as sum (1, 2, 3, 4)
  2. Then, in the function, a = 1, B = 2, arg = {3, 4}

More importantly, it can return multiple results at the same time, for example:

 
 
  1. Function s ()
  2. Return 1, 2, 3, 4
  3. End
  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? Here is an example:

 
 
  1. t =  
  2. {  
  3.  Age = 27 
  4.  add = function(self, n) selfself.Age = self.Age+n end  
  5. }  
  6. print(t.Age) 27  
  7. t.add(t, 10)  
  8. print(t.Age) 37 

However, the sentence t. add (t, 10) is a bit earthy, right? It doesn't matter, inLuaCan be abbreviated:

 
 
  1. T: add (10) is equivalent to t. add (t, 10)

Userdata and Thread

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

Is that the end? Of course not. Next, useLuaInterpreter to help you understand and practice. This article only helps you understandLua. If you have a programming Foundation, I believe thatLuaGet started.

Summary: AboutLua gamesScriptLanguageThe content of the Getting Started course guide is complete. I hope this article will help you!

Related Article

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.