Cocos2dx-lua mixed use with C + +

Source: Internet
Author: User
Tags addchild

This article is reproduced in http://www.cnblogs.com/zisou/p/cocos2dx-lua1.html

One of the above questions I think we need to think about before we use LUA, what are the advantages of LUA? What are the drawbacks? Find your own project positioning first

When to use it is necessary;

After one's own exploration, there are the following conclusions:

Advantages:

1, embedded script development can skip the platform market for independent game Resources update;

2, in the use of LUA development can reduce the use of C + + pointer reference error, nil type problem;

3, you can use the LUA table structure to accomplish object-oriented;

There is also a problem with the project positioning, that is, the development of games, with all Lua, or C + + binding Lua?

All Lua:

If you use full LUA, I recommend using Cocos2d-x touch to officially buy quick-cocos2dx! in Chengdu. The advantage of quick development is a

Word! Fast! Officially provided framework (Quicklua package) is currently 2.2 version (3.0 will also be synchronized later), I will make up for the configuration of quick development environment;

C + + binding Lua:

In project targeting, only a subset of the modules (activities, etc.) need to be developed using LUA, which must be halfway decent, from halfway bound to Lua, for C + + and

The cross-development of LUA, this kind of binding development is more popular, because C + + can take advantage of LUA to achieve self-updating, LUA can also rely on C + + with its

The lower level development ability completes the relatively complex development;

The above is an overview of the use of LUA, the following is a direct key link, will be implemented in Xcode and Eclipse cocos2dx+lua!

This article may be a little long, with small stool, melon seeds to watch;

———————————————————————————————————————————————————

With version cocos2dx2.2 version,

To manually bind Cocos2dx+lua in Xcode:

1, the first new construction of a new project, how to COCOS2DX, and eventually can be run up to Xcode;

2, add LUA Libs package under Libs folder after new good;

This is my new LUA project with Xcode, which comes with a package Lua folder;

You can also use COCOS2DX to bring your own:

After comparison, it was found that 4 directories were used, Cocos2dx_support,lua,luajit,tolua

3, add after completion point run will be error, because the lack of cocostudio this library, if you want to use Cocostudio after the project, then the Library guide in, if not

Then directly comment out the Cocostudio related can run up!

4,ok run up, we can use Lua script, we first simply write a test (function for C + + load a cclayer,cclayer has a

Background sprite picture)

(a) First we need to write the Lua script code first.

Testlua.lua

-- forccluaengine tracebackfunction __g__trackback__ (msg) print ("----------------------------------------") Print ("LUA ERROR:".. ToString (msg):"\ n") Print (Debug.traceback ()) Print ("----------------------------------------") endlocal function main ()--Avoid memory leak collectgarbage ("Setpause", -) CollectGarbage ("Setstepmul", the) Local Cclog=function (...) Print (string. Format (...) End Local Visiblesize=ccdirector:shareddirector (): Getvisiblesize () Local Origin=ccdirector:shareddirector (): getvisibleorigin () local function createlayermap () local Layerwroldmap =cclayer:create () Local BG= Ccsprite:create ("luaimg/bd.jpg") bg:setposition (origin.x+ Visiblesize.width/2+ the, ORIGIN.Y + visiblesize.height/2) layerwroldmap:addchild (BG,1)        returnLayerwroldmap End Ccdirector:shareddirector (): Getrunningscene (): AddChild (Createlayermap (),3,1) Endxpcall (Main, __g__trackback__)

If you have some programming experience, it is easy to learn lua,js this scripting language, to download the LUA tutorial online can be understood first!

(b) Before I had written a singleton method using the Publicluatodo class, mainly referring to the official to provide us with the Ccluaengine (LUA support engine)

This is a middleware tool class that operates LUA in COCOS2DX, and I've encapsulated it, how to use Lua's approach;

Below I paste the code directly:

PublicLuaTodo.h

#include"cocos2d.h"#include"script_support/ccscriptsupport.h"#include".. /.. /.. /lua/cocos2dx_support/ccluaengine.h"#include<string>using namespacestd; USING_NS_CC;classPublicluatodo: Publicccobject{ Public: Publicluatodo (void); ~publicluatodo (void); Staticpublicluatodo*getinstance (); //Execute LUA file    Static voidTodoluafile (stringLuapath); //executing LUA statements    Static voidTodoluastring (stringluastring); //execute a LUA-global approach    Static voidTodoluaglobalfunction (stringfounctionname);Private:    Staticpublicluatodo*m_instance;};

PublicLuaTodo.cpp

#include"PublicLuaTodo.h"Ccluaengine*Pengine; Publicluatodo* Publicluatodo::m_instance =NULL; Publicluatodo*publicluatodo::getinstance () {if(!m_instance) {m_instance=NewPublicluatodo (); }    returnm_instance;} Publicluatodo::P Ublicluatodo () {Pengine=ccluaengine::d efaultengine (); Ccscriptenginemanager::sharedmanager ()-Setscriptengine (Pengine); }voidPublicluatodo::todoluafile (stringLuapath) {std::stringPath = Ccfileutils::sharedfileutils ()Fullpathforfilename (Luapath.c_str ()); Pengine-Executescriptfile (Path.c_str ());}voidPublicluatodo::todoluastring (stringluastring) {Pengine-executestring (Luastring.c_str ());}voidPublicluatodo::todoluaglobalfunction (stringfounctionname) {Pengine-executeglobalfunction (Founctionname.c_str ());} Publicluatodo::~publicluatodo (void){   if(!pengine) {Pengine=NULL; }}

Is the structure of all the preparation of my project;

(c) Implement the LUA files that we have already shipped:

    String luafile = "Test/test.lua";    Publicluatodo::getinstance ()->todoluafile (luafile);

I wrote the last piece of code into the HelloApp inside of the Close method, it is very convenient to run up the new layer of LUA!

5, using the Tolua++ tool class implementation to invoke the C + + method in Lua

(a) In the project I also introduced an adaptation of the class VisbleRect.h is written in C + +, the main function is to get the coordinates of the screen in all directions,

Convenient to use the coordinate point after fitting. To use this class COCOS2DX provides the tool Tolua method, the principle is to pass this Tolua++ipa call through

The xx.pkg file created by yourself generates a class LuaCocos2d.cpp interface for LUA calls, and Lua can find a corresponding method in Lua

Use.

(ii) write the xx.pkg file that needs to be called:

Navigate to:/users/youmacname/cocos2dx.2.2/cocos2d-x-2.2/tools/tolua++, and write Visblerect.pkg file in this directory

To write the rules see Readme translation as follows:
1) enum keeps the same
2) Remove Cc_dll for the class defines, pay attention to multi inherites
3) Remove inline keyword for declaration and implementation
4) Remove public protect and private
5) Remove the decalration of class member variable
6) Keep Static keyword
7) Remove Memeber functions that declared as private or protected

Visblerect.pkg

classvisiblerect{Staticccrect getvisiblerect (); StaticCcpoint left (); StaticCcpoint Right (); Staticccpoint Top (); StaticCcpoint Bottom (); StaticCcpoint Center (); Staticccpoint lefttop (); Staticccpoint righttop (); Staticccpoint Leftbottom (); Staticccpoint Rightbottom ();};


(c) Modify the cocos2d.pkg in/cocos2dx.2.2/cocos2d-x-2.2/tools/tolua++ and add the $pfile "visiblerect.pkg" line

(d) Continue to modify the following path:

Navigate to:/cocos2dx.2.2/cocos2d-x-2.2/tools/tolua++/

Makefile file

cocos2d.pkg file

Change to the path you want to build yourself

(v) Open terminal run./build.sh, compile to generate new LuaCocos2d.cpp with interface

(vi) Copy the newly generated LuaCocos2d.cpp to our engineering directory

Corresponding Engineering catalogue

/users/youmacname/myluatest/myluatest/libs/lua/cocos2dx_support/

Replace the original LuaCocos2d.cpp

(vii) The direct XCODEX running run will error, need to add VisbleRect.h header files in the project LuaCocos2d.cpp path.

#include "/users/youmacname/myluatest/myluatest/classes/visiblerect.h"

A bit more run will not error, to this step should also understand the whole COCOCS2DX running LUA principle and mechanism!

Congratulations, you can use the static method provided in the Visiblerect! This means that LUA can also call C + +!!

Let's actually do a little bit of Lua.

Modify Test.lua

-- forccluaengine tracebackfunction __g__trackback__ (msg) print ("----------------------------------------") Print ("LUA ERROR:".. ToString (msg):"\ n") Print (Debug.traceback ()) Print ("----------------------------------------") endlocal function main ()--Avoid memory leak collectgarbage ("Setpause", -) CollectGarbage ("Setstepmul", the) Local Cclog=function (...) Print (string. Format (...) End--local visiblesize =ccdirector:shareddirector (): Getvisiblesize ()--local origin =ccdirector:shareddirector (): getvisibleorigin () local function createlayermap () local Layerwroldmap =cclayer:create () Local BG= Ccsprite:create ("luaimg/bd.jpg")                --bg:setposition (origin.x + visiblesize.width/2+ the, ORIGIN.Y + visiblesize.height/2) Bg:setposition (Visiblerect:center ()) Layerwroldmap:addchild (BG,1)        returnLayerwroldmap End Ccdirector:shareddirector (): Getrunningscene (): AddChild (Createlayermap (),3,1) Endxpcall (Main, __g__trackback__)

OK, run it after you're done.

So far we've finished tying Lua on Xcode and using tolua++ to call C + +!

———————————————————————————————————————————————————

Android tied Lua

If you have not configured the Android environment on your Mac, see this "cocos2d-x Environment Configuration-mac Configuration Chapter"

1, the same is the first to create a new project;

./create_project.py-project Xxx-package Com.xxx.xxx-language CPP

2, the new class that we just wrote on Xcode is ported (copy the corresponding directory on the line), and the corresponding. mk file is written

3, the project may be error, first import Libpluginprptocol COCOS2DX provided by the expansion pack

/users/youmacname/cocos2dx.2.2/cocos2d-x-2.2/plugin/protocols

Right button Myluatest Project->android->library->add Libpluginprptocol come in

4, this step is an important part of understanding how the Android project tied LUA works!

Follow, we need to add the corresponding

Local_whole_static_libraries + = Cocos_lua_static

Lua Static Library and we need LUA separate. So Android project

$ (call import-module,scripting/lua/proj.android)

OK, now we run a bit will be error!! And on the xcodex is the same reason! We have to replace the original luacocos2d.cpp!.

The true path to Android $ (call import-module,scripting/lua/proj.android) is as follows:

/users/youmacname/cocos2dx.2.2/cocos2dx2.2/scripting/lua/cocos2dx_support/

We need to replace the LuaCocos2d.cpp with/users/youmacname/cocos2dx.2.2/cocos2dx2.2/scripting/lua/cocos2dx_support/.

The following LuaCocos2d.cpp

And like iOS also want to modify the inside of the path, at this time the path should fill andriod below, can fill absolute path!

You can click on Android run to complete the above steps!!

The. So file was successfully generated, marking Android also running up!

The above is the Android project to manually bind and use tolua++ content!

This article is indeed a bit long, I hope to be useful to everyone! Lua Next I'll talk about how C + + and LUA data transfer values, intermodulation methods, etc. i have handled the class library;

————————————————————————————————————

This chapter Xcode source address: Baidu Cloud Disk

Cocos2dx-lua mixed use with 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.