使用版本cocos2dx2.2版本、呵呵呵呵
http://www.mamicode.com/info-detail-936871.html
1,cocos2dx_support,lua,luajit,tolua
2,添加之后报错,点run报错。是因为缺少cocostudio这个库
3,我们就可以使用lua脚本了,我们先简单写一个测试的
(功能为在c++加载一个CClayer,CClayer中有一个背景精灵图片)
首先我们需要先把lua脚本代码写出来
testlua.lua
-- for CCLuaEngine traceback function __G__TRACKBACK__(msg) print("----------------------------------------") print(LUA ERROR: " .. tostring(msg) .. \n) print(debug.traceback()) print() end local function main() -- avoid memory leak collectgarbage(setpause",100) collectgarbage(setstepmul5000) 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 + 80,origin.y + visibleSize.height / 2) layerWroldMap:addChild(bg,1) return layerWroldMap end CCDirector:sharedDirector():getRunningScene():addChild(createLayerMap(),128)">3,0)">) end xpcall(main,__G__TRACKBACK__)
在之前我已经写了一个单例方法使用的PublicLuaTodo类,主要是引用官方给我们提供的CCLuaEngine(LUA支持引擎)
PublicLuaTodo.h
#include cocos2d.h #include script_support/CCScriptSupport.h../../../lua/cocos2dx_support/CCLuaEngine.h #include <string> using namespace std; USING_NS_CC; class PublicLuaTodo:public CCObject { : PublicLuaTodo(void); ~PublicLuaTodo(); static PublicLuaTodo* getInstance(); //执行lua文件 static void toDoLuaFile( luapath); 执行lua语句 void toDoLuaString( luastring); 执行一个lua全局的方法 void toDoLuaGlobalFunction( founctionname); private: m_instance; };
PublicLuaTodo.cpp
PublicLuaTodo.h CCLuaEngine* pEngine; PublicLuaTodo* PublicLuaTodo::m_instance = NULL; PublicLuaTodo* PublicLuaTodo::getInstance() { if(!m_instance) { m_instance = new PublicLuaTodo(); } m_instance; } PublicLuaTodo::PublicLuaTodo() { pEngine = CCLuaEngine::defaultEngine(); CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine); } void PublicLuaTodo::toDoLuaFile( luapath) { std::string path = CCFileUtils::sharedFileUtils()->fullPathForFilename(luapath.c_str()); pEngine->executeScriptFile(path.c_str()); } void PublicLuaTodo::toDoLuaString( luastring) { pEngine->executeString(luastring.c_str()); } void PublicLuaTodo::toDoLuaGlobalFunction( founctionname) { pEngine->executeGlobalFunction(founctionname.c_str()); } PublicLuaTodo::~PublicLuaTodo() { pEngine) { pEngine=NULL; } }
执行我们已经写好的lua文件
string luafile = "test/test.lua"; PublicLuaTodo::getInstance()->toDoLuaFile(luafile);
我把上段代码写到了helloapp里面的关闭方法中,很方便就能运行起来lua新加的层
Android上面绑lua
1,同样也是先创建一个新工程
./create_project.py -project XXX-package com.xxx.XXX -language cpp
2,将刚才我们在Xcode上写的东西新加的类都移植(复制对应目录就行),并编写对应的.mk文件
原文链接:https://www.f2er.com/cocos2dx/339198.html