本文在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();
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_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
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