"Game development" small white learn lua (upper)

Source: Internet
Author: User

In many games, scripting languages are an integral part of many games that use Lua,js,python-class scripts that can help the development process in many ways. The scripting language can be used as a quick and easy way to initialize files into variables and game data. They are often favored by many game developers because of the fact that they have a little bit of time to improve productivity, creativity and extensibility. In this blog, horse will work with you to learn about the Lua scripting language.

  I. Setting up a LUA operating environment

  Learning any programming language is probably the first to build up its development environment, so as to write more code more practice. LUA has an interactive interpreter (Lua.exe) that you can use to validate small snippets of code, but for longer and more complex code, it's best to run with the LUA API of C/s, which is the code block required to run a LUA script from a C + + program:

extern " C " {    <Lua.h>    <lualib.h>    <lauxlib.h>}

The first step is to include the relevant header file, because Lua is a pure C library, so you must explicitly let the compiler know this, or you will encounter problems. It can be solved by using the # include and extern "C".

// contains the LUA library. If your compiler does not support this directive, then do not forget to include these libraries in your project settings #pragma comment (lib, "Lua.lib")#pragma comment (lib, " Lualib.lib)<iostream>int  main () {    // Create a LUAstate    Lua _state *pl=Lua_open ();}

Each running script file runs in a dynamically allocated data structure called Lua_state. Each call to a function in the LUA library requires that the Lua_state pointer be passed as a parameter to that function, so a LUA state must be created through Lua_open before running a LUA script file.

Open Standard library lua_open_base (PL) in Lua, luaopen_string ( PL), luaopen_table (PL), luaopen_math (PL), luaopen_io (PL);

There are several standard libraries in Lua that provide a range of function functions such as input and output, arithmetic calculations, string manipulation, and so on. The above line of code allows you to invoke these library commands in your script, just like the C + + #include响应的库一样.

  

if (int error=lua_dofile (PL,"lua_script.lua")! =0  ) {    std::cout <<"error! "<<Endl;     return -1;}

Use the Lua_dofile command to load, compile, and run LUA scripts. If the error occurs when running, it will return an incorrect code.

  

  Ii. LUA variables, types, operators, and conditional structures

Setting up a good environment can finally write some LUA code to practice practiced hand. But before we do, let's get familiar with Lua's variables, types, operators, and conditional structures (which can be very easy to learn if you have a previous programming language base).

  1.Lua variables

  Lua is a dynamic language, and unlike C++/java, variables can be assigned to any type of value (as with scripts such as Js,python), such as:

  

-- LUA script begins! name="masanxiaohuoer"print("name="): Name);p I=3.1415926name=Pipi=false

In Lua, annotations are usually started with "--", if you want to write multiple lines of comments, you can structure:--[[This is a comment]. In Lua, the semicolon behind each code can be written without writing, but semicolons are necessary when your code crosses the line. In Lua, multiple values can be assigned to multiple variables at the same time.

  

1,2,3,4

If the number of variables on the left side is more than the right one, then the extra variable is given a nil value, nil in Lua means meaningless, null (similar to NULL in C + +). If there is more value on the right, then the extra value will be discarded. In Lua, there are 3 different variables: Global (Global), local (partial), table fields (tables). If a variable is not modified with local, then it defaults to global. Before a variable is assigned a value, its value is nil.

  2.Lua type

  The following 8 basic data types are available in Lua:

(1) Nil null

Nil and other types are different, she used to denote meaningless, null values. Once a value has been given nil, it disappears, as if it had never existed.

(2) Number value

The number type is used to represent floating-point numbers. Inside Lua, this value is treated as double. Therefore, when passing a variable of type number to a C + + program, remember to map them to the appropriate correct type.

(3) String strings

The string type is of type, and you can use the ".." To link a two string. If one side of the type is not a string, then it is transformed into a string type and then connected.

(4) Boolean Boolean

The value type used to indicate true or FALSE, 0 or nil is false and the rest is true.

(5) Function functions

Unlike C + +, in Lua, a function is a type and can be assigned to a variable. So by using the name of that variable, you can call that function. Because Lua is a weakly typed language, neither the parameter list nor the return value requires a specified type. Here is a simple example of a sum of two numbers. In Lua, the function block ends with the end keyword.

  

add=function(b)return A +bEnd

If you're used to a language like Java or C + +, you might feel a little unfamiliar with the syntax. LUA provides another way to define a function that looks more like C++/java:

  

function Add (A,    b) return A +bEnd

Unlike C + +, LUA functions can return multiple variables at once, such as the following:

  

function Increse (A,    b) return a+ 1, B +1enda=2, b=4;A, B =  Increase (A, b)print(A, B)

(5) Table

Table is a very important and powerful data type in Lua, and you can think of tables as an associative array or a hash table. This means that you can not only index a table with integers, but also use any type of key value to index a table, and LUA tables are mixed types that can contain different data types.

  

--Create a tablemy_table={}--add some data to the tablemy_table[1]=2333my_table[2]=666my_table[3]="HelloWorld"--or you can initialize a table at oncemy_table={2333,666,"HelloWorld"}--Associated Indexmy_table[" One"]=2333my_table[6]="Study"--in addition to using [], we can also use. To access a valueMy_table.one =2333--functions can also be assigned to tablesfunctionAdd (A, b)returnA +bEndmy_table={}my_table["Add"]=AddPrint(My_table.add (2,3))

(6) UserData user data

The UserData type allows LUA variables to store custom C/+ + data. A variable of type UserData cannot be created and modified in Lua, only through the C + + interface (we will describe this method in the next article).

(7) Thread threads

With this type, we can generate and run new threads

  3. Logical operators

  There are three logical operators in Lua, namely: And,or, and not. They and C + + &&, | | And! Much like, and like C + +, they check the second condition only if necessary. Nil and False are false, others are true.

  4. Conditional structure

  Several conditional structures are provided in LUA for If\while\repeat\for. Several versions of Lua's if and while control structures are similar to C + +, except that the conditions in Lua do not need to be written in parentheses.

  

ifa==4  Then    Print(" Four")Else     Print(" Other")End--While Loop whilea<= -  Thena=a+1EndPrint(a)--the while and if statements have ended with the end keyword--repeat and until keywords are used together, like this:Repeata=a+1    Print(a)untila== ---the for structure has two versions, one for the number and one for the table--syntax for a for loop for a number: forVar=low_value,high_value,step DoxxxxxxEnd--Example forA=Ten, -,2  DoPrint(a)End

As with C + +, you can also use break to exit the loop.

There is also a for loop that iterates through the table

-- Grammar  for inch  Do xxxxx End

Key and value represent keys and values respectively, and table is the one we want to traverse.

  

-- example my_table={a=1, b=2, c=3}for     Print(k,v)End

By now, we've had a little bit of knowledge of LUA, but we can't use it to serve our game programs. In the next section, we will work together on the interface between LUA and C + + and how LUA can be used in cocos2d-x and unity engines.

Horse Lad
Source: http://www.cnblogs.com/msxh/p/6033679.html
Please respect the results of other people's work, let the sharing become a virtue, welcome reprint. In addition, the article in the expression and code, if there is inappropriate, welcome criticism. Leave your footprints and welcome the comments!

"Game development" small white learn lua (upper)

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.