The communication Process code instance for Lua and C + + _lua

Source: Internet
Author: User
Tags bool lua

Previous Chapter Portal: http://www.jb51.net/article/55088.htm

In this chapter we'll learn a little demo, the scene from the previous chapter: C + + Gets a string of global variables from LUA.

1. Introduction of header Files

Let's take a look at what we need to use LUA in C + +.

Copy Code code as follows:

/*
FileName: HelloLua.h
Description: Lua Demo
Creator: Stupid wood.
Date Created: 2012.12.24
*/

#ifndef __hello_lua_h_
#define __hello_lua_h_

#include "Cocos2d.h"

extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
};

using namespace cocos2d;

Class Hellolua:public Cclayer {
Public
Create_func (Hellolua);
virtual BOOL init ();

Static ccscene* scene ();
};

#endif


Do you see the red bold code? (Narrator: Where is it?) Where is it? )
In this:

Copy Code code as follows:

extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
};

(Narrator: Your Sister paper ...) Can't you just post it and ask? ~! )

Remember, Lua is a C language library, so use the extern "C" declaration in C + + to let the compiler know.
With this, we can start using LUA.
(Narrator: Wait, there's always something wrong with it. =)

Ah, yes, there is one thing, but this does not need us to do, that is the introduction of the LUA Library, no library, how we include the header file is useless.

But it doesn't matter, Cocos2d-x was supposed to support Lua, so this is a step we saved, and to be on the safe side, I checked to support LUA when I created a new demo project.

It is recommended that you first create a cocos2d-x project that supports LUA, and that you can compile and run, and then continue looking down
(Narrator: Can't you teach us to introduce a LUA library?) = =)

I teach? I do not understand ~

2. Start using

To take a look at our CPP file, we're going to start using LUA. ~!

Copy Code code as follows:

#include "HelloLua.h"

ccscene* Hellolua::scene () {
ccscene* scene = Ccscene::create ();
cclayer* layer = Hellolua::create ();
Scene->addchild (layer);

return scene;
}

BOOL Hellolua::init () {
lua_state* PL = Lua_open ();
Luaopen_base (PL);
Luaopen_math (PL);
Luaopen_string (PL);

* 1. Execute LUA script, return 0 Rep Success * *
/* 2. Reset the top index of the stack * *
/* 3. Determine whether the value of the top of the stack is of type string, and returns a value of not 0 for success.
* 4. Get the value of the top of the stack * *
  
Lua_close (PL);
return true;
}

In order not to suddenly frighten everyone with a lot of code, I deleted some of the code, let's take a look at the current code:
1 Hellolua is a scene (Narrator: Nonsense ...). )
2 Hellolua has an init function (Narrator: Your sister paper, get to the point, okay?) )
3) I like to narrate the slot ~ (Narrator: ...)
4 to use LUA, first have to have a lua_state, what is this? I quote "The game of artificial intelligence programming case Pristine" (191 pages): "Every running script file is run in a dynamically assigned data structure called lua_state". If it's not understood, it doesn't matter, and we think of lua_state as a LUA body, and Lua can't do anything without the body.
5) Next see a few words: luaopen_base (PL); luaopen_math (PL); luaopen_string (PL);
LUA has some standard libraries, and to use these libraries, you use luaopen_** to load these libraries
6 and then finally there is a sentence: Lua_close (PL), a look at the know, used to free memory.
7) What about the narrator? (Narrator: Bad mood ...) Don't want to spit the Groove)

3. Execute LUA Scripts

Now we're going to refine our code step-by-step, and it's easy to execute the LUA script and see:

Copy Code code as follows:

BOOL Hellolua::init () {
lua_state* PL = Lua_open ();
Luaopen_base (PL);
Luaopen_math (PL);
Luaopen_string (PL);

* 1. Execute LUA script, return 0 Rep Success * *
int err = Lual_dofile (PL, "Hellolua.lua");
Cclog ("Open:%d", err);

/* 2. Reset the top index of the stack * *
Lua_settop (PL, 0);
Lua_getglobal (PL, "myname");

/* 3. Determine whether the value of the top of the stack is of type string, and returns a value of not 0 for success.
* 4. Get the value of the top of the stack * *
  
Lua_close (PL);
return true;
}


(Narrator: No Spit all ... Did you put the 2nd step out of your mind? = =)
We also need to create a new Lua file, which is simple, create a new text file, and change the suffix name to Lua. Now we're going to create a Hellolua.lua file:
Copy Code code as follows:

--Hellolua.lua file
myname = "Beauty Girl"


(Narrator: Don't always ignore me. The 2nd step is what is going on?! )
Well, the Lua file also has, in C + + as long as the call Lual_dofile can execute the LUA script, note that the lua_state must also be passed as parameters to the Lual_dofile, as has been said before, the body can not be less.

4. Reset the top index of the stack and put the global variables on the stack

Didn't anyone find out? I put the 2nd step out.
(Narrator: Ah, hello, ~!. I've said it many times, I found it, ~!. )

Lua_settop (PL, 0); To ensure that the index of the top of the stack is set to 0, because we operate the stack based on the index. After 0, the index of the first element we put into the stack is 1.

That, Lua_getglobal (PL, "myname"); It looks like it's getting the value of myname this global variable from LUA, but that's not the case, though ultimately.
(Narrator: Your Sister paper, speak clearly)

As we've said before, Lua and C + + can't communicate directly, and they want to communicate through the stack.
Therefore, Lua_getglobal (PL, "myname"); just put the myname on the stack, then LUA will look through myname to the global table, find myname corresponding string "Beauty Girl", and put it on the stack. (No. 01 Chapter of the time introduced the steps, remember?) Do not remember the suggestion that you go to see ~)
(Narrator: Stop!) Let me buffer ... )
Narration
1.c++ put the myname on the stack.
2.lua get myname from stack
3.lua use MyName to LUA global table lookup get myname corresponding string, get "Beauty Girl" string, then put back to stack
4. The last C + + can get the "Beauty Girl" string from the stack?
Good ~!. Understand ~)

5. The final step, C + + get string

Let's take a look at the complete code:

Copy Code code as follows:

bool Hellolua::init () {
    lua_state* PL = Lua_open ();
    luaopen_base (PL);
    Luaopen_math (PL);
    luaopen_string (PL);

   /* 1. Execute LUA script, return 0 for Success */
    int err = Lual_dofile (PL, "Hellolua.lua"); br>     Cclog ("Open:%d", err);

   /* 2. Reset stack Top index */
    lua_settop (PL, 0);
    Lua_getglobal (pl , "myname");

   /* 3. Determines whether the type of the value on the top of the stack is string, and returns a value other than 0 for success */
    int isstr = lua_isstring (PL, 1);
& nbsp;   Cclog ("Isstr =%d", isstr);

   /* 4. Get the value of the top of the stack */
    const char* str = lua_tostring (PL, 1);
    Cclog ("Getstr =%s", str);

    lua_close (PL);
    return true;
}


Lua_getglobal has done a lot of work, now on the stack on the "Beauty Girl" string, we just have to pick it.
There are a number of ways to get the value of the stack, corresponding to different variable types:
Copy Code code as follows:

Lua_toboolean
Lua_tonumber
Lua_tocfunction
Lua_tostring

I don't have all the examples, now we're going to use lua_tostring to get the value of the top of the stack.
Finally, in AppDelegate.cpp to set the default startup scene to our Hellolua scene, run the project in debug mode, you will see the following log:
Copy Code code as follows:

open:0
ISSTR = 1
Getstr = Beauty Girl

OK, this chapter to this knot ... (Narrator: Wait!) What's the 3rd step? You haven't explained yet, ~!. )

By the right, Lua also provides a number of functions for us to determine the types of variables in the stack, such as lua_isstring, Lua_isnumber, and so on, and lua_tostring functions. Returns a non-0 value indicating the correct type.
Generally before the value must be judged, not the program is likely to crash unexpectedly ~!
(Narrator: Frighten = =!) )

Well ~ This chapter ends here ~

6. Gift of

Finally tell everyone a smiling ~
That is the use of Lua_pop (PL, 1); Can clear the data on the specified stack ~
Pop, Twinkle, man!
(Narrator: I help him explain ...) It's a little secret ... Not smiling = =)

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.