cocos2d-x lua c++ 相互调用代码中直接调用注册
原博客链接http://blog.csdn.net/vpingchangxin/article/details/21382229
我用的是 cocos2d-x 2.2.2 我也是参考 himi博客中的文章 但是他那个我没有跑通 不多废话 下面是我的代码
如有lua api 等疑问点开链接看himi的文章 http://blog.csdn.net/xiaominghimi/article/details/8816887
AppDelegate.h
#ifndef __APP_DELEGATE_H__
#define __APP_DELEGATE_H__
#include "cocos2d.h"
/**
@brief The cocos2d Application.
The reason for implement as private inheritance is to hide some interface call by CCDirector.
*/
class AppDelegate : private cocos2d::CCApplication
{
public:
AppDelegate();
virtual ~AppDelegate();
/**
@brief Implement CCDirector and CCScene init code here.
@return true Initialize success, app continue.
@return false Initialize failed, app terminate.
*/
virtual bool applicationDidFinishLaunching();
/**
@brief The function be called when the application enter background
@param the pointer of the application
*/
virtual void applicationDidEnterBackground();
/**
@brief The function be called when the application enter foreground
@param the pointer of the application
*/
virtual void applicationWillEnterForeground();
};
#endif // __APP_DELEGATE_H__
AppDelegate.cpp
#include "cocos2d.h"
#include "CCEGLView.h"
#include "AppDelegate.h"
#include "CCLuaEngine.h"
#include "SimpleAudioEngine.h"
#include "Lua_extensions_CCB.h"
#include "lua_extensions.h" // lua_cjson
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "Lua_web_socket.h"
#endif
#include "Lua_callCppTest.h"
using namespace CocosDenshion;
USING_NS_CC;
AppDelegate::AppDelegate()
{
}
AppDelegate::~AppDelegate()
{
SimpleAudioEngine::end();
}
bool AppDelegate::applicationDidFinishLaunching()
{
// initialize director
CCDirector *pDirector = CCDirector::sharedDirector();
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
// turn on display FPS
pDirector->setDisplayStats(false);
// set FPS. the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
// CCEGLView::sharedOpenGLView()->setDesignResolutionSize(1024, 768, kResolutionShowAll);
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(960, 640, kResolutionExactFit);
#endif
// register lua engine
CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);
CCLuaStack *pStack = pEngine->getLuaStack();
lua_State *tolua_s = pStack->getLuaState();
tolua_extensions_ccb_open(tolua_s);
// 添加lua_cjson
luaopen_lua_extensions(tolua_s);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
pStack = pEngine->getLuaStack();
tolua_s = pStack->getLuaState();
tolua_web_socket_open(tolua_s);
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY)
CCFileUtils::sharedFileUtils()->addSearchPath("script");
#endif
test lua call cpp function /
Lua_callCppTest::sharedHD()->callCppFunction(tolua_s);
std::string path = CCFileUtils::sharedFileUtils()->fullPathForFilename("main.lua");
pEngine->executeScriptFile(path.c_str());
///c++ call lua function
Lua_callCppTest::sharedHD()->callLuaFunction("testCppTolua");
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground()
{
CCDirector::sharedDirector()->stopAnimation();
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
CCDirector::sharedDirector()->startAnimation();
SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
Lua_callCppTest.h
//
// Lua_callCppTest.h
// WestwardJourneyGaiden
//
// Created by vin on 14-3-17.
//
//
#ifndef __WestwardJourneyGaiden__Lua_callCppTest__
#define __WestwardJourneyGaiden__Lua_callCppTest__
#include <iostream>
#include "cocos2d.h"
using namespace cocos2d;
using namespace std;
#include "CCLuaEngine.h"
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
};
class Lua_callCppTest {
public:
static Lua_callCppTest* sharedHD();
void callCppFunction(const char* luaFileName);
static int cppFunction(lua_State* ls);
void callCppFunction(lua_State* ls);
/*
callLuaFunction : 调用lua函数
luaFileName = lua文件名
functionName = 所要调用Lua中的的函数名
*/
const char* callLuaFunction(const char* functionName);
private:
static bool _isFirst;
static Lua_callCppTest* _shared;
const char* getFileFullPath(const char* fileName);
~Lua_callCppTest();
};
#endif /* defined(__WestwardJourneyGaiden__Lua_callCppTest__) */
Lua_callCppTest.cpp
//
// Lua_callCppTest.cpp
// WestwardJourneyGaiden
//
// Created by vin on 14-3-17.
//
//
#include "Lua_callCppTest.h"
#include "GameHttp.h"
bool Lua_callCppTest::_isFirst;
Lua_callCppTest* Lua_callCppTest::_shared;
Lua_callCppTest::~Lua_callCppTest(){
CC_SAFE_DELETE(_shared);
_shared=NULL;
}
Lua_callCppTest* Lua_callCppTest::sharedHD(){
if(!_isFirst){
_shared = new Lua_callCppTest();
}
return _shared;
}
const char* Lua_callCppTest::getFileFullPath(const char* fileName){
return CCFileUtils::sharedFileUtils()->fullPathForFilename(fileName).c_str();
}
#pragma mark - 废弃不要了
void Lua_callCppTest::callCppFunction(const char* luaFileName){
// lua_State* ls = CCLuaEngine::defaultEngine()->getLuaStack()->getLuaState();
lua_State* ls = CCLuaEngine::defaultEngine()->getLuaStack()->getLuaState();
luaopen_base(ls);
luaopen_math(ls);
luaopen_string(ls);
// luaL_openlibs(ls);
/*
Lua调用的C++的函数必须是静态的
*/
lua_register(ls, "cppFunction", cppFunction);
int isOpen = luaL_dofile(ls, getFileFullPath(luaFileName));
if(isOpen!=0){
CCLOG("Open Lua Error: %i", isOpen);
return;
}else{
CCLog("------sddd");
}
}
void Lua_callCppTest::callCppFunction(lua_State* ls){
/*
Lua调用的C++的函数必须是静态的
*/
lua_register(ls, "cppFunction", cppFunction);
}
int Lua_callCppTest::cppFunction(lua_State* ls){
int luaNum = (int)lua_tonumber(ls, 1);
int luaStr = (int)lua_tostring(ls, 2);
CCLOG("Lua调用cpp函数时传来的两个参数: %i %s",luaNum,luaStr);
/*
返给Lua的值
*/
lua_pushnumber(ls, 321);
lua_pushstring(ls, "Himi");
// GameHttp * request = GameHttp::create();
// request->testHttp();
/*
返给Lua值个数
*/
return 2;
}
const char* Lua_callCppTest::callLuaFunction(const char* functionName){
lua_State* ls = CCLuaEngine::defaultEngine()->getLuaStack()->getLuaState();
//
// int isOpen = luaL_dofile(ls, getFileFullPath(luaFileName));
// if(isOpen!=0){
// CCLOG("Open Lua Error: %i", isOpen);
// return NULL;
// }
lua_getglobal(ls, functionName);
lua_pushstring(ls, "Himi");
lua_pushnumber(ls, 23);
lua_pushboolean(ls, true);
/*
lua_call
第一个参数:函数的参数个数
第二个参数:函数返回值个数
*/
lua_call(ls, 3, 1);
const char* iResult = lua_tostring(ls, -1);
CCLog("cpp print:%s",iResult);
return iResult;
}
lua代码 main.lua
function __G__TRACKBACK__(msg)
print("----------------------------------------")
print("LUA ERROR: " .. tostring(msg) .. "\n")
print(debug.traceback())
print("----------------------------------------")
end
local function main()
collectgarbage("setpause",500)
collectgarbage("setstepmul",5000)
require "utils.helper" -- 全局变量
require "utils.resource" -- 资源图片路径统一配置
require "layer/LoginLayer" -- login
local scene = CCScene:create()
local layer = LoginLayer:create()
scene:addChild(layer)
CCDirector:sharedDirector():runWithScene(scene)
------------ test lua cpp ---------
local num,str = cppFunction(999,"I'm a lua string")
print("从cpp函数中获得两个返回值:",num,str)
end
function testCppTolua(_logStr,_logNum,_logBool)
print("Lua 脚本打印从C传来的字符串:",_logStr,_logNum,_logBool)
return "call lua function OK"
end
xpcall(main, __G__TRACKBACK__)