Lua script steps in C ++ (1) (Getting Started)

Source: Internet
Author: User

From: http://www.acejoy.com/bbs/viewthread.php? Tid = 1931 & extra = Page % 3d1

Now, more and more C ++ servers and clients are integrated with Script support, especially in the online gaming field. The script language has penetrated into all aspects. For example, you can add a script on your client, this script will display new data on the interface, help you complete some tasks, or help you view the status of other players or NPCs... And so on.

However, I think the combination of scripting language and C ++ is far faster than the special effects you see in the game. It can be applied to all fields, such as your most common application fields. For example, you can use a text editor, write a script language, and load it with your program to produce a very beautiful interface. Or one or two text languages will let your program send data to the server. Isn't that cool?
I was thinking about writing an article about mainstream scripting languages Lua and python, but it seems so boring, so I will introduce them one by one. I believe you understand C ++, after reading my articles, I will be very interested in scripting. I think of a story I heard before. When I was a Java creator, in the first place, I would like to take a simple, non-simple small example, continue to expand, and finally become a complex and perfect program. Today, I will try this experiment.

Of course, I am not sure that I know the scripting language well. I can only say that I have mastered it a little. I have been using it for a few years. please correct me if you are biased.
Next, let's start with Lua! (This article is intended for beginners)

Lua language (http://www.lua.org/), presumably many programmers have heard of it, as far as I know, because of the World of Warcraft in the face of its loading, it suddenly became a lot of game developers competing to research object, as for this Brazilian creator, I am not going to talk about it much. If you are interested, You can Google it. In fact, there are a lot of textbooks and examples about Lua on the Internet. To be honest, I almost couldn't understand it that year. At that time, I was very depressed and felt that Lua was so complicated and worried, after that, I began to study it a little bit and thought it was actually quite concise. The information on the Internet may be biased towards some functions, resulting in complicated logic and code. Later, I concluded that learning a scripting language can be a little bit relaxed, but the effect will be better.

Before talking about the code, I would like to talk about some features of Lua. These features help you to clearly understand the ins and outs in complicated code calls. In fact, you can use more than 10 Lua APIs, which is complicated. Basically, it is composed of so many APIs. As for what they are, the following article will introduce them. Another important concept is stack. Lua interacts with other languages and exchanges data through stacks. In fact, you can think of a stack as a box. If you want to give it data, you need to put the data one by one in order. Of course, Lua has completed the execution, there may be results returned to you, so Lua will use your boxes to continue to store them one by one. If you want to retrieve the returned data from the top of the box, what if you want to obtain your input parameters? It is also very simple. Just retrieve the data according to the number of returned data on the top, and then retrieve the data one by one in order. However, we would like to remind you that the stack position is always relative. For example,-1 indicates the current stack top, and-2 indicates the next data position at the top of the current stack. Stack is the place where data is exchanged. There must be some stack concepts.

Well, the basic Lua syntax is not mentioned here. There are many Baidu syntaxes.
First go to The http://www.lua.org/to download a latest Lua code (now stable version is lua-5.1.4 ). Its code is written in C, so it is easy to be compatible with many platforms.
In Linux, the directory SRC has a dedicated makefile. It's easy. You don't need to do anything. Just specify the location for compilation.
In Windows, take vs2005 as an example to create an empty static library project (it is best not to use the pre-compilation header and remove the option of the pre-compilation header ), then, copy all the files under SRC (except makefile) to the project. Add these files to your project. Compile the file and generate *. llib (* the name of your Lua database). After that, create a directory Lib, copy it, and create an include folder to put the Lua under your project directory. h, lualib. h, lauxlib. h. copy it. All right, with these two folders, you can use Lua in your project.
All right, the materials are ready. Let's see how to write a simple Lua program.

Create a file named sample. Lua
Add such code.
Function func_add (x, y)
Return X + Y;
End

This is a standard Lua syntax, a function that implements simple A + B operations and returns the operation results.
Save and exit.
In Lua, you can return multiple data.
For example:
Function func_add (x, y)
Return x + y, x-y;
End

This indicates that the first parameter is the result of addition, and the second parameter is the result of subtraction. There is no concept of Type in Lua. Of course, when C ++ accepts such a return value, it is also very simple. Please look down.
Well, the materials are ready. Let's see how the C ++ program calls it.
First, create a class to load the Lua file and execute function operations. This is called cluafn.
To load this Lua file, we should load the file first and then call different functions according to the normal idea. Well, let's do it.

Extern "C"
{
# Include "LUA. h"
# Include "lualib. h"
# Include "lauxlib. H"
};

Class cluafn
{
Public:
Cluafn (void );
~ Cluafn (void );

Void Init (); // initialize the Lua Object Pointer Parameter
Void close (); // close the Lua object pointer

Bool loadluafile (const char * pfilename); // load the specified Lua File
Bool callfilefn (const char * pfunctionname, int nparam1, int nparam2); // execute the function in the specified Lua File

PRIVATE:
Lua_state * m_pstate; // This Is The Lua State object pointer. You can correspond to one Lua file.
};

Well, there are so many header files. It's not complicated at all. I think you'll be more happy with seeing CPP, because there are few codes. I will introduce you to functions one by one.

Void cluafn: Init ()
{
If (null = m_pstate)
{
M_pstate = lua_open ();
Lual_openlibs (m_pstate );
}
}

Initialization function, standard code, nothing to mention, lua_open () is to return you a Lua Object Pointer, lual_openlibs () is a good thing, in lua4, initialization to do a lot of code, for example, loading Lua's string library, I/O library, Math library, and so on. A lot of code is not necessary because you need to use these libraries, it doesn't make much sense except to practice your typing ability, because the code is fixed. As a result, Lua's creators modified a lot after 5, which is one of them. In a word, it helped you load all the basic Lua libraries you may use.

Void cluafn: Close ()
{
If (null! = M_pstate)
{
Lua_close (m_pstate );
M_pstate = NULL;
}
}

As the name implies, when I have used up, close my Lua object and release resources. Well, there is nothing to say about standard writing.

Bool cluafn: loadluafile (const char * pfilename)
{
Int nret = 0;
If (null = m_pstate)
{
Printf ("[cluafn: loadluafile] m_pstate is null./N ");
Return false;
}

Nret = lual_dofile (m_pstate, pfilename );
If (nret! = 0)
{
Printf ("[cluafn: loadluafile] lual_loadfile (% s) is file (% d) (% s ). /n ", pfilename, nret, lua_tostring (m_pstate,-1 ));
Return false;
}

Return true;
}

This is a bit interesting. Load a Lua file.
Here I want to explain in detail, because Lua is a script language that will be compiled only when the Lua file itself is loaded.
Therefore, we recommend that you put the file into program initialization whenever possible, because when you execute the lual_dofile () function, Lua will enable the syntax analyzer, analyze whether your script syntax complies with the Lua rules. If you randomly upload a file, Lua will tell you that the File Syntax is incorrect and cannot be loaded. If your Lua script is large and has many functions, the syntax analyzer will be time-consuming. Therefore, when loading, try to put it in a proper place. In addition, for a Lua file, loading lual_dofile () repeatedly makes no sense except that it will make your CPU Hot.

Maybe you set "[cluafn: loadluafile] lual_loadfile (% s) is file (% d) (% s)" to printf ). /n ", pfilename, nret, lua_tostring (m_pstate,-1); what is this sentence interesting? Here I will first talk about What lua_tostring (m_pstate,-1) is doing. Do you still remember that Lua is based on stack to transmit data? So how do I know what the error is if an error is reported? Lual_dofile returns an int. I cannot traverse this nret in Lua. h.
What do you mean? Well, the Lua creator has long been thinking about you, but you need to move your mind a little bit. When the Lua creator analyzes your syntax in the syntax analyzer, he finds an error. A piece of text tells you what the error is. It puts the string at the top of the stack. So how can we get the string at the top of the stack? Lua_tostring (m_pstate,-1).-1 indicates that the current stack position is relative to the top of the stack. Of course, you can also look at some other weird data in the stack. You can try it with 1, 2, 3 (these are absolute positions, and-1 is relative. However, I believe what you get is hard to understand, because when a Lua object is executed, it will use many stacks for data exchange. What you see may be the data in the exchange. In other words, this sentence means "[cluafn ::
Loadluafile] lual_loadfile (file name) is file (error number) (specific error description)./N"

Bool cluafn: callfilefn (const char * pfunctionname, int nparam1, int nparam2)
{
Int nret = 0;
If (null = m_pstate)
{
Printf ("[cluafn: callfilefn] m_pstate is null./N ");
Return false;
}

Lua_getglobal (m_pstate, pfunctionname );

Lua_pushnumber (m_pstate, nparam1 );
Lua_pushnumber (m_pstate, nparam2 );

Nret = lua_pcall (m_pstate, 2, 1, 0 );
If (nret! = 0)
{
Printf ("[cluafn: callfilefn] Call function (% s) error (% d)./N", pfunctionname, nret );
Return false;
}

If (lua_isnumber (m_pstate,-1) = 1)
{
Int nsum = lua_tonumber (m_pstate,-1 );
Printf ("[cluafn: callfilefn] sum = % d./N", nsum );
}

Return true;
}

This function is used to pass in the function name and parameters for execution in your Lua file.
Lua_getglobal (m_pstate, pfunctionname );
This function verifies whether your Lua function is in the Lua file you are currently loading and points the pointer to the position of this function.

Lua_pushnumber (m_pstate, nparam1); <-corresponds to your X Parameter
Lua_pushnumber (m_pstate, nparam2); <-corresponds to your y Parameter

This is a well-known stack-based operation that pushes your parameters to Lua's data stack. For Lua syntax to obtain your data.
Lua_pushnumber () is a number, and lua_pushstring () is a string...

Then you will ask, if I have a class pointer or something of my own, how can I press it in? Don't worry. There are some methods, of course. But first, let's take a look at how to do it. In the next few lectures, I will tell you more powerful Lua stack Press Art.
It should be noted that the order of stack pressure, right, simply put, is the parameter from left to right, the first stack on the left, and the last stack on the right.

Nret = lua_pcall (m_pstate, 2, 1, 0 );
This statement means to execute this function. 2 indicates the number of input parameters, and 1 indicates the number of output parameters. Of course, if you change the Lua function
Return x + y, x-y;
The code needs to be changed to nret = lua_pcall (m_pstate, 2, 2, 0 );
See, huh, huh, very easy.
Of course, if the function fails to be executed, it will trigger nret. I am a lazy here. If you want to get it, why is it wrong? You can use lua_tostring (m_pstate,-1) to find the top stack. Do you understand? Is it a bit of a feeling?

Lua_isnumber (m_pstate,-1)
This statement is used to determine whether the element at the top of the stack is a number. If the execution is successful, the stack top should be your data return value.
Int nsum = lua_tonumber (m_pstate,-1 );
Printf ("[cluafn: callfilefn] sum = % d./N", nsum );
This nsum is the returned result.
Of course, you will ask, what should I do if return x + y, x-y?
Int nsum = lua_tonumber (m_pstate,-1 );
Int nsub = lua_tonumber (m_pstate,-2 );
Done. No. According to the order of pressure stack. Well, is there another feeling? Right, stack is the core of data interaction. The degree of understanding and use of Lua is actually the flexible use and operation of the stack.
Okay. Your first Lua program is finished! It's not actually Hello world.
Okay. Let's take a look at how to write the main function. I believe everyone will write it.

# Include "luafn. h"

Int _ tmain (INT argc, _ tchar * argv [])
{
Cluafn luafn;

// Luafn. initclass ();

Luafn. loadluafile ("sample. Lua ");
Luafn. callfilefn ("func_add", 11, 12 );
Getchar ();

Return 0;
}

All right. Let's build it and see if you want the result? If yes, you have already taken the first Lua step.
I have been writing for an hour. Let's have a drink. In the next lecture, I will strengthen this luafn class and let it do more for me. In the end, I will ask you to create a Windows form using the Lua file. And draw various buttons, lists, and check boxes. Is it cool? Use text to create a program? I'm so excited. Well, indeed, Lua can do it for you. As long as you have patience to watch it...

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.