使用cocos2d-x 3.x lua 开发时 lua与c++交互

前端之家收集整理的这篇文章主要介绍了使用cocos2d-x 3.x lua 开发时 lua与c++交互前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本文在himi的文章上简单加了些自己的理解:himi文章链接:http://blog.csdn.net/xiaominghimi/article/details/8816887

下面直接上代码


.h文件

#include "cocos2d.h"

#include "CCLuaEngine.h"


using namespace cocos2d;


extern "C" {

#include "lua.h"

#include "lualib.h"

#include "lauxlib.h"

};


class Lua_callCppTest

{

public:


static Lua_callCppTest* getInstance();

//将需要被调用函数注册lua

void callCppFunction(lua_State* ls);

//需要被调用函数

static int cppFunction(lua_State* ls);

private:

static Lua_callCppTest* _shared;

const char* getFileFullPath(constchar* fileName);

~Lua_callCppTest();

};

--------------------------

.cpp文件

#include "Lua_callCppTest.h"


Lua_callCppTest* Lua_callCppTest::_shared =nullptr;


const char* Lua_callCppTest::getFileFullPath(const char* fileName)

{

returnFileUtils::getInstance()->fullPathForFilename(fileName).c_str();

}


Lua_callCppTest::~Lua_callCppTest()

{

CC_SAFE_DELETE(_shared);

_shared = nullptr;

}


Lua_callCppTest* Lua_callCppTest::getInstance()

{

if (_shared == nullptr)

{

_shared = newLua_callCppTest();

}

return_shared;

}


void Lua_callCppTest::callCppFunction(lua_State* ls)

{

//把需要被调用方法注册lua

lua_register(ls,"cppFunction",cppFunction);

}


int Lua_callCppTest::cppFunction(lua_State* ls)

{

//取出从lua中返回的参数

int luaNum = (int)lua_tonumber(ls,1);

log("Lua_callCpplua 函数中获得的参数: %d",luaNum);

//将需要的参数传入lua

lua_pushstring(ls, "li yue");

//返回给lua值的个数

return 1;

}

----------------

lua文件


local function main()


collectgarbage("collect")

-- avoid memory leak

collectgarbage("setpause",100)

collectgarbage("setstepmul",5000)


cc.FileUtils:getInstance():addSearchPath("src")

cc.FileUtils:getInstance():addSearchPath("res")



local director = cc.Director:getInstance()


director:getOpenGLView():setDesignResolutionSize(640,1136,cc.ResolutionPolicy.EXACT_FIT)


--create scene


local scene = require("GameScene")

local gameScene = scene.create()


if cc.Director:getInstance():getRunningScene() then

cc.Director:getInstance():replaceScene(gameScene)

else

cc.Director:getInstance():runWithScene(gameScene)

end

-- lua里直接调用c++函数

local num = cppFunction(1234)


print("cpp函数中获得的返回值:",num);


end


----------------------

AppDelegate.cpp里的调用

bool AppDelegate::applicationDidFinishLaunching()

{

auto engine = LuaEngine::getInstance();

ScriptEngineManager::getInstance()->setScriptEngine(engine);

//这里要注意执行代码的顺序,应该先调用这个方法

Lua_callCppTest::getInstance()->callCppFunction(engine->getLuaStack()->getLuaState());

if (engine->executeScriptFile("src/main.lua"))

{

return false;

}

return true;

}


----------------------

打印结果:

cocos2d: Lua_callCpp lua函数中获得的参数: 1234

cocos2d: [LUA-print] cpp函数中获得的返回值:li yue

原文链接:https://www.f2er.com/cocos2dx/346920.html

猜你在找的Cocos2d-x相关文章