Communication Process code examples for LUA and C + +

Source: Internet
Author: User

C + + Gets a string of global variables from LUA.

1. Introduction of header Files

Let's see what we need to use LUA in C + +.

Copy CodeThe code is as follows:
/*
File name: HelloLua.h
Description: Lua Demo
Created by: Dumb 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 code in red bold? (Narrator: Where is it?) Where the hell is it? )
In this:

Copy CodeThe code is as follows:
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
};


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

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

Oh, yes, there's one less thing, but this doesn't need to be done, it's a library of Lua, no library, and we don't have any use for the header file.

But it doesn't matter, Cocos2d-x originally supported Lua, so we saved this step, and for the sake of insurance, I checked the support LUA when I created the 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 LUA libraries?) = =)

I teach? I don't know ~

2. Start using

Take a look at our CPP file and we're going to start using Lua!

Copy CodeThe code is 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 for Success */
/* 2. Reset stack Top Index */
/* 3. Determine whether the type of the value at the top of the stack is a string, and return a value other than 0 indicates success */
/* 4. Get the value of the top of the stack */
  
Lua_close (PL);
return true;
}

In order not to suddenly a lot of code to scare everyone, I put some of the code first deleted, we take a look at the current situation of this code:
1) Hellolua is a scene (Narrator: Nonsense ... )
2) Hellolua has an init function (Narrator: Your sister's paper, get into the chase, okay?) )
3) I like to narrate the Groove ~ (Narrator: ...)
4) to use LUA, first have to have a lua_state, what is this? I quote a word from the "game AI Programming Case" (191 pages): "Each running script file runs in a dynamically allocated data structure called Lua_state." If you don't understand, it doesn't matter, and we think of lua_state as a LUA body, and Lua can't do anything without it.
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, it is necessary to load them with luaopen_**.
6) and then finally there is a sentence: Lua_close (PL), a look to know, to release memory.
7) What about the narrator? (Narrator: Bad mood ...) Do not want to spit groove)

3. Execute the LUA script

Now let's step through our code and execute the LUA script very simply, and see:

Copy CodeThe code is 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");
Cclog ("Open:%d", err);

/* 2. Reset stack Top Index */
Lua_settop (PL, 0);
Lua_getglobal (PL, "myName");

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


(Narrator: Do not spit groove are not ... 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 let's create a Hellolua.lua file:

Copy CodeThe code is as follows:
--Hellolua.lua file
MyName = "Beauty Girl"



(Narrator: Don't always ignore me.) What's the 2nd step?! )
Well, LUA files also have, in C + + as long as the call Lual_dofile can execute LUA script, notice, must be lua_state also as a parameter to Lual_dofile, previously said, the body can not be less.

4. Reset the top index of the stack and place the global variable on the stack

You didn't find it? I put the 2nd step out.
(Narrator: Ah Hello ~!) I said many times, I found AH ~! )

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

So, Lua_getglobal (PL, "myName"); At first glance, it seems that the value of the global variable is obtained from Lua, but that is not the case, although in the end it is myname.
(Narrator: Your sister's paper, say it clearly.)

As we've said before, Lua and C + + can't communicate directly, and they need to communicate through stacks.
So, Lua_getglobal (PL, "MyName"), just put MyName in the stack, and Lua will go through the myName to the global table, find the myName corresponding string "Beauty Girl", and then put it in the stack. (The steps introduced in the No. 01 chapter, remember?) Don't remember the suggestion everyone go to see ~)
(Narrator: Stop!) Let me cushion ... )
Narration
1.c++ put the myname on the stack.
2.lua getting myname from the stack
3.lua use MyName to go to LUA global table find get myname corresponding string, get "Beauty Girl" string, and then put back to stack
4. Finally C + + can get the "Beauty Girl" string from the stack?
Good! Understand ~)

5. The final step, C + + Gets the string

Let's take a look at the complete code:

Copy CodeThe code is 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");
Cclog ("Open:%d", err);

/* 2. Reset stack Top Index */
Lua_settop (PL, 0);
Lua_getglobal (PL, "myName");

/* 3. Determine whether the type of the value at the top of the stack is a string, and return a value other than 0 indicates success */
int isstr = lua_isstring (PL, 1);
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, and now there's a "Beauty Girl" string on the stack, and we just have to fetch it.
There are many ways to get the value of a stack, which corresponds to a different variable type:

Copy CodeThe code is 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, set the default boot scenario to our Hellolua scene in AppDelegate.cpp, run the project in debug mode, and you will see the following log:

Copy CodeThe code is as follows:
open:0
ISSTR = 1
Getstr = Beauty Girl


OK, this chapter to this knot ... (Narrator: Wait!) What's the 3rd step? You have not explained Ah, the Soul Light ~! )

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 are corresponding. Returns a non-0 value indicating the type is correct.
Generally in the value before you have to judge, not the program is likely to crash unexpectedly!

6. The Gift of

Finally tell everyone a smiling ~
That is with Lua_pop (PL, 1); You can clear the data on the specified stack ~

Communication Process code examples for LUA and C + +

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.