Lua experience (1)

Source: Internet
Author: User

 

I have studied Lua over the past few days. I mainly focus on the integration between Lua and VC and write the code in the VC Host Program, then, call the code of the Host Program in Lua (or interface or component, whatever you call it), hoping to use the script to control the behavior of the main program. This is actually an architecture that separates businesses and uses scripts to control them. Some people may call such scripts as business engines and workflows.

 

Why Lua?

Because it is a scripting language that can be very tightly integrated with C/C ++, our program is written in VC ++. The other reason is that it is famous, even wow uses Lua to provide APIs for gamers to modify their game behavior, so I can't find any reason to reject it.

 

What is Lua? Where can I obtain Lua?

I did not go into details. I searched a lot on the Internet and only talked about its official internet cafe www.lua.org. Here I can find the Lua application. I used the version 5.1.4 released by Lua, download the source code version.

 

Integration of Lua and vc mfc?

  • 1. Including Lua: You need to use Lua. Of course, you must first include it in our project. You can use lib/DLL or static Lib, of course, you can also put the entire Lua code into our project and then compile it, Because Lua only has several hundred kb and is very small... The method that contains the entire code is described as follows:
  • A) create a project in vc mfc (for example, dialog base project)
  • B) Go to the file tab page of the project, create a folder, and. C ,. H files are included. Note that there are a few unnecessary files, Lua. c. wmain. c. luac. c. After the folder is included, select all. c file, right-click setting and choose not using precompiler file. Find the file by yourself. After this step is completed, compile it immediately. It should be okay!
  • C) There are two ways to include Lua into the project: dynamic library and static Lib. You can try it yourself.
  • 2. Include the Lua header file somewhere (starting from the mfclua1dlg. cpp file) and declare a lua_state pointer, as shown below:

Extern "C"

{

# Include "Lua. H"

# Include "lualib. H"

# Include "lauxlib. H"

}

Lua_state * Lua;

 

Call the following code in a proper place (I am in oninitdialog). The function of this Code is to open some necessary libraries:

Lua = lua_open ();

If (LUA)

{

Luaopen_base (LUA );

Luaopen_table (LUA );

Luaopen_string (LUA );

Luaopen_math (LUA );

Luaopen_debug (LUA );

// Luaopen_io (LUA );

}

 

When Lua is used up, call the following sentence to close the Lua database:

Lua_close (LUA );

Now, Lua has completely become a part of our program. Let's compile it to see if it can be passed...

 

Interaction between Lua and MFC?

 

After Lua becomes a part of our program, we need to use it. Remember that our goal is to use a script program to control the execution process of our host program. We need to complete two steps, first, use the MFC program to call the Lua function, and second, use Lua to call the MFC function. The following content may be difficult for beginners to understand, I will try to put it simply...

 

1. MFC calls the Lua function. A stackdump function is used here to address the issue of the Interaction stack between the main program and Lua. The following describes the issue of the Interaction stack.

 

First, we use NotePad to create a test. Lua. The content is an addition function:

 

Function add (x, y)

Return X + Y;

End

 

Then, call it in VC, the following code. when reading this code, ignore the stackdump function. You only need to know that it is a function that outputs the content of the Interaction stack between Lua and VC, by the way, you can create a button's click function and put the code in it:

 

Stackdump (LUA );

Lual_dofile (Lua, "test. Lua"); // parse the Lua File

Stackdump (LUA );

Lua_getglobal (Lua, "add"); // obtain a global label Add. At the same time, the Add function is pushed to the stack.

Stackdump (LUA );

Lua_pushnumber (Lua, 1); // press the first parameter into the stack.

Stackdump (LUA );

Lua_pushnumber (Lua, 2); // The second parameter pressure Stack

Stackdump (LUA );

// Lua_call (Lua, 2, 1 );

If (lua_pcall (Lua, 2, 1, 0 )! = 0) // execute the Add function

{

Afxmessagebox ("lua_pcall error! ");

Return;

}

Stackdump (LUA );

Int d = (INT) lua_tonumber (Lua,-1); // After the function is executed, the execution result is pushed to the stack. Therefore, the result value is obtained from the top number, -1 refers to the value of the top stack.

Cstring STR;

Str. Format ("% d", d );

Afxmessagebox (STR );

Stackdump (LUA );

Lua_pop (Lua, 1); // clear the value from the stack, pop (POP) A Value

Stackdump (LUA );

 

After analyzing this code, we probably know that the process of calling the Lua function is: dofile --> function name pressure Stack --> parameter pressure stack in sequence --> lua_pcall execution (execution result pressure stack) --> retrieve the execution result (if there are multiple results, retrieve multiple results from the stack ...), In this way, we can easily call the functions in Lua. In fact, we need to know what happened in the stack...

 

2. Lua calls the MFC function. For example, if we want to call a MSG function in Lua, a window will pop up to display the string we want to display, and the return value will be 1 "msgok! "String.

 

The Lua file is like this. The first sentence is to call the MSG function, and the second sentence is to test whether the returned string is "msgok! ":

C = MSG ("123 ");

MSG (C );

 

In the MFC program:

First, write a function to be exported. Many articles call it glue function ):

Static int MSG (lua_state * l)

{

Const char * S1 = lual_checkstring (L, 1); // test whether the first parameter is in the string format and obtain this string

Stackdump (L );

MessageBox (null, S1, "caption", mb_ OK );

Lua_pop (Lua, 1); // clear the string in the stack

Stackdump (L );

Lua_pushlstring (L, "msgok! ", 6); // press the return value into the stack

 

// The number of returned values

Return 1;

}

 

Then export the function as follows:

Lua_pushcfunction (Lua, MSG );

Lua_setglobal (Lua, "MSG ");

 

Then execute the Lua file just now. Remember to execute lua_open () first:

Lual_dofile (Lua, "test. Lua ");

 

The result of running is to jump out of two messageboxes consecutively. The first is 123, and the second is "msgok! ", Indicates that the returned string is received by Lua. If the second line of Lua does not receive its return value, the returned value is automatically discarded.

If you need to return multiple values, we should take the following sentence:

Lua_pushlstring (L, "msgok! ", 6); // press the return value into the stack

// The number of returned values

Return 1;

 

Changed:

Lua_pushlstring (L, "msgok! ", 6); // press the return value into the stack

Lua_pushlstring (L, "haha! ", 5); // press the return value into the stack

// The number of returned values

Return 2;

 

In this way, we can get two return values in the Lua file as follows:

C, D = MSG ("123 ");

Then C and D are respectively "msgok! "And" haha! "Two strings. This automatic mechanism is more convenient to use.

 

3. Interactive Stack

 

The above two calls are actually applicable to the Lua stack, so we need to understand the concept of the Interaction stack between Lua and VC (what is the stack? Please refer to the data structure book ...) Lua and VC interact through this stack. The access functions of this stack include lua_gettop, lua_settop, lua_tostring, lua_toxxx, and so on. We need to know when a function call occurs, what happened in the stack. I used a stackdump function above. When we call it, we can clearly see what happened in the stack.

First, we need to know that the number from the top of the stack is-1,-2, and the number from the bottom of the stack is 1, 2.

If lua_gettop (L, 1) is used, the first element at the bottom of the stack is obtained. Lua_gettop (L,-1) is the first element to get the top of the stack. Lua_pop () (L, 1) is to pop up an element at the top of the stack. lua_pop () (L, 2) is to pop up two elements at the top of the stack.

 

Okay, I wrote a pass, and finally the implementation of this stackdump function:

Int stackdump (lua_state * l)

{

Int ntop = lua_gettop (l); // obtain the number of elements in the stack. Stack top position.

Outputdebugstring ("the length of stack is % d/N", ntop); // the top position of the output stack.

For (INT I = 1; I <= ntop; ++ I)

{

Int T = lua_type (L, I );

Outputdebugstring ("% s:", lua_typename (L, t); // here, typename converts enumeration of the type into a string and is the type name. It is not the position in the stack.

Switch (t)

{

Case lua_tnumber:

Outputdebugstring ("% F", lua_tonumber (L, I ));

Break;

Case lua_tstring:

Outputdebugstring ("% s", lua_tostring (L, I ));

Break;

Case lua_ttable:

// Outputdebugstring ("% s/n", lua_tostring (L, I ));

Break;

Case lua_tfunction:

// Outputdebugstring ("% s/n", lua_tostring (L, I ));

Break;

Case lua_tnil:

Outputdebugstring ("is null ");

Break;

Case lua_tboolean:

Outputdebugstring ("% s", lua_toboolean (L, I )? "True": "false ");

Break;

Default:

Break;

}

Outputdebugstring ("/N ");

}

Return 0;

}

 

This article focuses on the integration of Lua and Vc, compilation of Lua source code and VC project together, VC calls Lua's code, and Lua calls VC's code, return values and multiple return values, interactive stacks, and Element Information in the output interactive stack. The next article will talk about how to avoid blocking scripts, Lua and multithreading usage, and so on.

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.