Lua scripting and C + + interaction (i)

Source: Internet
Author: User
Tags lua

Now, more and more C + + servers and clients are embedded in script support, especially in the field of online games, scripting language has penetrated into all aspects, such as you can add a script to your client, this script will help you to display the new data on the interface, or to help you complete some tasks, or help you check the status of other players or NPCs ... And so on

But I think that the combination of scripting language and C + + is far more dramatic than the effects you see in the game. It can be used in a range of areas, such as your most common application areas. For example, you can use a text editor, write a scripting language, and then use your program to load, it will produce a very beautiful interface. Or one or two words of text language, it will let your program send data to the server, is not very cool?
Originally I want to write an article about the mainstream scripting language Lua and Python, but feel so boring, so separate to introduce, I believe the C + + understand you, read my article will have a strong interest in scripting language, I think of a story I heard before, When the creator of Java was lecturing, he began by taking a simple small example that could not be simple, expanding continuously, and finally becoming a complex and perfect program. Today I would like to experiment with it, hehe.

Of course, I do not dare to say that the scripting language at all, can only say a little grasp some, used a few years, the biased place please correct me.
Now, let's start with lua!. (This article is for beginners)

Lua language (http://www.lua.org/), presumably a lot of programmers have heard, as far as I know, because "World of Warcraft" in the face of its loading, it suddenly became a lot of game developers competing for research objects, as for this Brazilian creator, I do not introduce too much, we are interested can Google. In fact, there are a lot of textbooks and examples of Lua on the internet, really, for the year I, almost do not understand, at that time very depressed, feel the complexity of LUA, some fear, then sank to a little bit of research, I think it is quite concise. It's just that the information on the web may be biased towards certain functions, resulting in complex logic and code. Later summed up, in fact, learning a scripting language, can hold a relaxed mentality a little bit of research, but the effect will be better.

Before I speak the code, I would like to say some of the features of Lua that will help you to clearly master the ins and outs of the complex code calls. In fact, you can often use the LUA API, but more than 10, and then complex logic. It's basically so many APIs. As for what they are, the following article will describe it. Another important concept is the stack. LUA interacts with other languages and exchanges data, which is done through stacks. In fact, simple explanation, you can think of the stack as a box, you want to give him data, you have to put the data in order one by one, of course, lua execution, there may be results returned to you, then LUA will also use your box, one after another to continue to put down. And you take out the return data, and you want to remove it from the top of the box, if you want to get your input parameters? It is also very simple, according to the number of return data at the top, and then in order to take out one by one, on the line. But here to remind you, about the position of the stack is always relative, for example-1 represents the current stack top, 2 represents the current top of the stack the position of the next data. Stack is the place of data exchange, must have some concept of the stack.

Well, the basic LUA syntax is not here to say, Baidu a bit more.
Go to http://www.lua.org/first to download a new LUA code (now the stable version is lua-5.1.4). Its code is written in C, so it's easy to be compatible with many platforms.
Under Linux, there is a special makefile under the directory src. Very simple, do not have to do anything, specify the location to compile.
Under Windows, take VS2005 as an example, create an empty static library project (preferably without using precompiled headers, remove the precompiled Header option), and then copy all the files under SRC (except makefile) to the project. Then add these files to your project, compile, generate a *.llib (* is your LUA library name), OK, set up a directory lib, copy it over, and then create an include folder, Copy the lua.h,lualib.h,lauxlib.h in your project directory. All right, take these two folders and you can use LUA in your project.
OK, the material is up, let's see how to write a simple LUA program.

(1) Lua program

(2) C + + program (header file)

extern "C"{#include"lua.h"#include"Lualib.h"#include"Lauxlib.h"};classcluafn{ Public: Cluafn (void); ~cluafn (void); voidInit ();//initializing Lua object pointer parameters    voidClose ();//turn off Lua object pointers    BOOLLoadluafile (Const Char* Pfilename);//loading the specified LUA file    BOOLCallfilefn (Const Char* Pfunctionname,intNPARAM1,intNPARAM2);//executes a function in the specified LUA filePrivate: Lua_state* M_PSTATE;//This is the LUA state object pointer, you can have a LUA file corresponding to a};

(3) C + + program (. cpp file)

#include"CLuaFn.h"Cluafn::cluafn (void{m_pstate = NULL;};//Why do you say that?Cluafn::~cluafn (void){};//initialization functionvoidCluafn::init () {if(NULL = =m_pstate) {M_pstate= Lua_open ();//returns a Lua object pointerLual_openlibs (m_pstate);//loaded all the LUA base libraries you might have used    }}//close LUA objects and release resourcesvoidCluafn::close () {if(NULL! =m_pstate)        {lua_close (m_pstate); M_pstate=NULL; }}BOOLCluafn::loadluafile (Const Char*pfilename) {    intNret =0; if(NULL = =m_pstate) {printf ("[Cluafn::loadluafile]m_pstate is null./n"); return false; }    //when loading the file, try to put it in the initialization of the program.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;}BOOLCluafn::callfilefn (Const Char* Pfunctionname,intNPARAM1,intnParam2) {    intNret =0; if(NULL = =m_pstate) {printf ("[Cluafn::callfilefn]m_pstate is null./n"); return false; }    //Verify that your LUA function is in the LUA file you are currently loading and point the pointer to the function locationLua_getglobal (M_pstate, pfunctionname); //Press Stack (order: left-to-right parameter): first parameterLua_pushnumber (M_pstate, nParam1); //Press stack: second parameterLua_pushnumber (M_pstate, nParam2); //execute this function, 2 is the number of input parameters, 1 is the number of return valuesNret = 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)    {        intNSum = Lua_tonumber (M_pstate,-1); printf ("[cluafn::callfilefn]sum =%d./n", NSum); }    return true;}

(4) C + + program (main file)

 #include  cluafn.h   " int  Main (int  argc, char  * argv[]) {Cluafn Luafn;    Luafn.init (); Luafn.loadluafile (  sample.lua   "    ); Luafn.callfilefn (  func_add  Span style= "color: #800000;" > ", 11 , 12     );    GetChar ();  return  0  ;}  

Note: The comments in the program are already exhaustive, and the code is not explained here. After downloading and installing LUA, the appropriate libraries are also introduced in the VS2010. As follows:

At this point, the build succeeds and runs, and if the following interface appears, it succeeds!

Lua scripting and C + + interaction (i)

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.