本文在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_callCpp从lua 函数中获得的参数: %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
总结以上是内存溢出为你收集整理的使用cocos2d-x 3.x lua 开发时 lua与c++交互全部内容,希望文章能够帮你解决使用cocos2d-x 3.x lua 开发时 lua与c++交互所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)