Lua usage tips (1)

Source: Internet
Author: User

These days to study Lua, the main focus is the integration between Lua and VC, the code is written in the VC host program, and then call the host program in LUA code (or interface, components, whatever you call), I hope to use the script to control the behavior of the main program. This is actually an architecture that separates business from scripting, and some people might call this script a business engine, a workflow, and so on. http://hovertree.com/

Why Choose LUA?

Because it is a script language that can be tightly combined with C + +, and our program is written in VC + +, and the other is because of its fame, even wow all use LUA to provide APIs for players to modify their game behavior, I can not find any reason to reject it.

What is LUA? Where to get LUA?

In detail do not say, a search on the internet a lot, only to say that its official Internet cafes: www.lua.org, here you can find the application of Lua, LUA released version, I use 5.1.4, download is the source code version.

Integration of LUA and VC MFC?

    • 1, including Lua: To use LUA, of course, you have to include it in our project, you can have Lib/dll way, you can also use the static LIB, of course, you can also put the entire LUA code into our project, and then compile, because Lua is only hundreds of k, very small ... A way to include the entire code I say:
    • A) Create a new project in VC MFC (e.g. Dialog Base project)
    • b) Go to the File tab in the project, create a new folder, and then include all of the. c,. h files in Lua, and note that there are several that do not contain, LUA.C, WMAIN.C, LUAC.C, after the inclusion, select all the. c files under this folder, then right-click setting, select the not using Precompiler file, find out for yourself ha. This step is done immediately compile, should be no problem!
    • c) There are dynamic libraries and static Lib two ways to include LUA in the project, you can try it.
    • 2, somewhere (I was at the beginning of the MFCLua1Dlg.cpp file) contains the LUA header file, and declares a lua_state pointer, as follows:

extern "C"

{

#include "Lua.h"

#include "Lualib.h"

#include "Lauxlib.h"

}

Lua_state *lua;

In the right place (I'm in OnInitDialog) call the following piece of code, which is the function of opening 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 you are finished using LUA, call the following sentence to close the LUA library:

Lua_close (LUA);

Okay, so far, Lua has completely become part of our program, try compiling it to see if it's going to go through ...

The interaction between Lua and MFC?

After Lua becomes part of our program, we also want to use it, to remember that our goal is to use the script to control the execution of our host program, then we have to complete two steps, one is to use the MFC program calls LUA function, and the second is to invoke the MFC function with LUA, The following content for beginners may start a bit difficult to understand, please wake up more than spirit, I will try to simply say ...

1, MFC call LUA function, here to use a stackdump function, is about the main program and LUA interaction stack problem, the following will be specific to the problem of the interaction stack.

First we create a Test.lua with Notepad, which is an additive function:

function add (x, y)

return x + y;

End

Then VC call it, such as the next piece of code, look at this code, the first to ignore the Stackdump function, just need to know that it is a output Lua and VC interactive stack content function, on, you can create a button click function, and then put this code in:

Stackdump (LUA);

Lual_dofile (LUA, "Test.lua"); Interpreting and analyzing LUA files

Stackdump (LUA);

Lua_getglobal (LUA, "add"); Takes a global label add, takes the Add function and pushes the stack

Stackdump (LUA);

Lua_pushnumber (LUA, 1); Press the first parameter into the stack.

Stackdump (LUA);

Lua_pushnumber (LUA, 2); The second parameter presses the 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 stacked, so the top number is the result value, -1 is the value of the top of the stack.

CString str;

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

AfxMessageBox (str);

Stackdump (LUA);

Lua_pop (LUA, 1); Clears the value from the Stack, POPs (POPs) a value

Stackdump (LUA);

A good analysis of this code, we probably know that the process of invoking the LUA function is: dofile--〉 function name stack--〉 parameter stack--〉lua_pcall execution (execution result stack)--〉 take out the execution results (if there are more than one, remove multiple from the stack ...) , so that we can easily invoke the functions in Lua, in fact, to know what's going on in the stack ...

2, Lua calls MFC functions, such as we want to invoke a MSG function in Lua, can pop up a window to display the string we want to display, and then the return value is 1 "msgok!" String.

Lua file is this, the first sentence is to call the MSG function, the second sentence is the test returns the string is not "msgok!" :

c = MSG ("123");

MSG (c);

The MFC program is like this:

First write a function that will be exported, and many of the articles call it the glue function (glue functions):

static int Msg (lua_state* L)

{

const char *S1 = lual_checkstring (L, 1); Tests whether the first parameter is a string and obtains the 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.

This return refers to the number of return values

return 1;

}

The function is then exported as follows:

Lua_pushcfunction (LUA, MSG);

Lua_setglobal (LUA, "MSG");

Then just execute the LUA file, and remember to Lua_open () before executing it:

Lual_dofile (LUA, "Test.lua");

The result is a continuous jump out of two MessageBox, the first is 123, the second is "msgok!", indicating that the string we returned was received by Lua, the second line of Lua we did not receive its return value, the return value will be automatically discarded.

If you need to return more values, we want to put the following sentence:

Lua_pushlstring (L, "msgok!", 6); Press the return value into the stack.

This return refers to the number of return values

return 1;

Switch

Lua_pushlstring (L, "msgok!", 6); Press the return value into the stack.

Lua_pushlstring (L, "haha!", 5); Press the return value into the stack.

This return refers to the number of return values

return 2;

This way we can get two return values in the Lua file as follows:

C,d = MSG ("123");

That C and D are "msgok!", respectively. and "haha!" Two strings. This automatic mechanism is still relatively convenient to use.

3. Interactive stack

The above two calls are actually practical for the LUA stack, so we need to understand a concept, what is the stack of the interaction between Lua and VC? Please refer to the data structure of the book ha ... Lua and VC are through this stack to achieve interaction, the access function of this stack has lua_gettop,lua_settop,lua_tostring,lua_toxxx and so on, we have to understand when a function call occurs, the stack is what happened. I use a stackdump function above, and when we call it, we can see exactly what's going on in the stack.

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

If you use Lua_gettop (L, 1), you get the first element on the bottom of the stack. Lua_gettop (L,-1) is the first element that gets the top of a stack. Lua_pop () (l, 1) pops an element of the top of the stack, Lua_pop () (L, 2) ejects two elements of the top of the stack.

Well, write a pass, and finally the implementation of this stackdump function:

int Stackdump (lua_state* L)

{

int nTop = Lua_gettop (L); Gets the number of elements in the stack. The position of the top of the stack.

OutputDebugString ("The Length of the stack is%d/n", nTop); Top position of output stack

for (int i = 1; I <= nTop; ++i)

{

int t = lua_type (L, i);

OutputDebugString ("%s:", Lua_typename (L, t)); The TypeName here is to turn the enumeration of types into a string, which is the type name. is not a 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 is mainly about the integration of Lua and VC, the LUA source code and VC project compiled together, VC calls LUA code, LUA call VC code, return value and multiple return values, interactive stacks, output interactive stack element information, the next article will say how to avoid blocking the script, The use of Lua and multithreading, among other things.

http://www.cnblogs.com/roucheng/

Lua usage tips (1)

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.