[Wood Cocos2d-x 027] Lua (Chapter 02nd): demo of Lua and C ++ hand in hand

Source: Internet
Author: User

[Wood Cocos2d-x 027] Lua (Chapter 02nd): demo of Lua and C ++ hand in hand

 

Chapter 1 portal: http://blog.csdn.net/musicvs/article/details/8440707

 

In this chapter, we will learn a small demo, that is, the scenario in the previous chapter: C ++ obtains a global variable string from Lua.

 

 

What do you mean? Flowers? No, it's your heart ~

Reprinted please note, original address: http://blog.csdn.net/musicvs/article/details/8440919

 

Body:

 

1. Introduce the header file

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

/* File name: hellolua. h Description: Lua demo created by: Stupid wood (csdn blog: http://blog.csdn.net/musicvs) creation date: 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

Have you seen the code in red bold? (Narrator: Where? Where ?)

Here:

Extern "C "{

# Include <Lua. h>

# Include <lualib. h>

# Include <lauxlib. h>

};

(Narrator: Your sister paper... Can't you post it first and ask again ?~!)

 

Remember, Lua is a C language library, so you must use the extern "C" declaration in C ++ to let the compiler know.

With this, we can start using Lua.

(Narrator: Wait, it always feels a bit wrong =)

 

Ah, by the way, there is still a few things, but we don't need to do this. It is to introduce the Lua library, and there is no library. It is useless to include header files.

But it doesn't matter, Cocos2d-x would have supported Lua, So we save this step, for the sake of insurance, I checked support Lua when creating a demo project.

We recommend that you first create a Cocos2d-x project that supports Lua, and can compile and run, and then continue to look down ~

(Narrator: Can you tell us to introduce the Lua library? =)

 

I teach? I don't understand ~

 

2. Start Using

Let's take a look at our CPP file. We're starting to use Lua ~!

# 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 the Lua script and return 0 to indicate success * // * 2. reset the top index of the stack * // * 3. determines whether the type of the value at the top of the stack is string. If the return value is not 0, the result indicates success * // * 4. obtain the value of the top stack */lua_close (PL); Return true ;}

 

In order not to scare everyone with a lot of code at once, I deleted some of the code first. Let's take a look at the current situation of this Code:

1) hellolua is a scenario (Narration: Nonsense ...)

2) hellolua has an init function (Narration: Do you get started with your sister paper ?)

3) I like narration ~ (Narrator :....)

4) To use Lua, you must first have a lua_state. What is this? One sentence I quoted from the book "the essence of Artificial Intelligence programming cases in games" (page 1): "Every running script file runs in a dynamically allocated data structure called lua_state ". If we don't understand it, it doesn't matter. We regard lua_state as a Lua body, and Lua cannot be physically absent when doing anything.

5) Next I will see a few words: luaopen_base (PL); luaopen_math (PL); luaopen_string (PL );

Lua has some standard libraries. To use these libraries, you must use luaopen _ ** to load these libraries.

6) then there is another sentence: lua_close (PL), which is used to release the memory.

7) What about narration? (Narrator: in bad mood... Don't want to vomit)

 

3. Execute the Lua script

Now let's improve our code step by step. It's easy to execute the Lua script. Let's take a look:

Bool hellolua: Init () {lua_state * PL = lua_open (); luaopen_base (PL); luaopen_math (PL); luaopen_string (PL);/* 1. execute the Lua script and return 0 to indicate 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. determines whether the type of the value at the top of the stack is string. If the return value is not 0, the result indicates success * // * 4. obtain the value of the top stack */lua_close (PL); Return true ;}

 

(Narrator: It won't work if you don't speak... Are you sure you want to release Step 1? =)

We also need to create a new Lua file, which is simple. Just create a text file and change the suffix to Lua. Create a hellolua. Lua file:

-- Hellolua. Lua file myname = "Beauty girl"

 

(Narrator: don't always ignore me. Okay... What happened in step 1 ?!)

Okay, the Lua file also exists. In C ++, you only need to call lual_dofile to execute the Lua script. Note that you must pass the lua_state parameter to lual_dofile. As mentioned above, the body cannot be less.

 

 

4. Reset the stack top index and place the global variables in the stack.

No one found it? I also released step 1 ~

(Narrator: Ah, hello ~! I have said this many times. I have discovered it ~!)

 

Lua_settop (PL, 0); is used to confirm that the index at the top of the stack is set to 0, because we operate the stack based on the index. After 0 is set, the index of the first element in the stack is 1.

So what is lua_getglobal (PL, "myname? Why is it optimistic that the value of the global variable "myname" is obtained from Lua, but this is not the case, even though this is the case in the end.

(Narrator: Your sister paper. Make it clear)

 

As we have said before, Lua and C ++ cannot communicate directly and must communicate through stacks.

Therefore, lua_getglobal (PL, "myname"); just puts myname in the stack, and then Lua searches for the global table through myname and finds the string "Beauty girl" corresponding to myname ", put it in the stack. (Do you remember the steps described in Chapter 01st? I suggest you check it out if you don't remember it ~)

(Narrator: Stop! Let me buffer ...)

(Narration:

1. c ++ put myname on the stack

2. Lua acquires myname from the stack

3. Lua uses myname to search for the string corresponding to myname In The Lua global table to obtain the "Beauty girl" string, and then puts it back to the stack.

4. In the end, C ++ can obtain the "Beauty girl" string from the stack?

Good ~! Understand ~)

 

5. In the last step, C ++ obtains the string

Let's take a look at the complete code:

Bool hellolua: Init () {lua_state * PL = lua_open (); luaopen_base (PL); luaopen_math (PL); luaopen_string (PL);/* 1. execute the Lua script and return 0 to indicate 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. determines whether the type of the value at the top of the stack is string. If the return value is not 0, the result indicates success */INT isstr = lua_isstring (PL, 1); cclog ("isstr = % d ", isstr);/* 4. obtain the top stack value */const char * STR = lua_tostring (PL, 1); cclog ("getstr = % s", STR); lua_close (PL); Return true ;}

 

Lua_getglobal has completed a lot of work, and now there is a "Beauty girl" string on the stack, we just need to get it.

There are many methods to obtain stack values, which correspond to different variable types:

Lua_toboolean

Lua_tonumber

Lua_tocfunction

Lua_tostring

I will not illustrate it all. Now we need to use lua_tostring to obtain the value of the stack top.

Finally, in appdelegate. cpp, set the default startup scenario to our hellolua scenario. Run the project in debug mode and you will see the following logs:

Open: 0

Isstr = 1

Getstr = beauty girl

Okay, this chapter ends... (narrator: Wait! What is Step 1? You have not explained it yet ~!)

 

By the way, Lua also provides many functions for us to determine the type of variables in the stack, such as lua_isstring and lua_isnumber, which correspond to functions such as lua_tostring. If the return value is not 0, the type is correct.

Generally, you have to judge before the value. It is not possible for the program to crash unexpectedly ~!

(Narrator: Scared = !)

 

Good ~ This chapter ends now ~

6. Complimentary

Finally, I will tell you a smile ~

That is, you can use lua_pop (PL, 1); To clear data on the specified stack ~

Hacker, transient ~

(Narrator: Let me explain it to him... It's a secret... Not smile =)

 

.

.

 

 

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.