首页 > 代码库 > 关于在Cocos2dx引擎中手动绑定C++到Lua

关于在Cocos2dx引擎中手动绑定C++到Lua

虽然大多数写的代码是Lua脚本,但是仍然会遇到单纯的使用Lua语言解决不了的问题,而只好要先用C++写好想要的功能,然后留好接口给Lua调用,

那么问题来了,怎么将C++写好的函数绑定到Lua中呢。。。

当然Cocos2dx3.x版本的应该集成了绑定这一功能,但是下面我要说的是绑定固定的函数到Lua中。

先在C++中实现自己的静态函数(此处只贴出声明.h):

 1 // 2 //  TestBind.h 3 //  testMoveTo 4 // 5 #include <stdio.h> 6 #include <iostream> 7 #include "cocos2d.h" 8 #include "lua.h" 9 using namespace std;10 11 class TestBind{12 public:13     static string getWorld(string prefix);14 };

开始绑定:

////  TestBind_luabinding.h//  testMoveTo//extern "C"{#include <lua.h>#include <lauxlib.h>#include <lualib.h>#include <tolua++.h>}extern int luaopen_TestBind_luabinding(lua_State* luaState);////  TestBind_luabinding.cpp//  testMoveTo//#include "TestBind_luabinding.h"#include <iostream>#include "tolua_fix.h"#include "LuaBasicConversions.h"#include "TestBind.h"#define BIND_PREFIX std::string("bind")int TestBind_getWorld(lua_State* luaState){    int topIndex = lua_gettop(luaState);    assert(topIndex == 1);//此处的 1指的是该函数具有几个参数        const char *prefix = lua_tostring(luaState, -1);//此处的 -1指的是参数在该函数的参数列表中从后往前是第几个    if (!prefix) {        generror(luaState, "TestBind.getWorld - #1\n");    }    std::string word = TestBind::getWorld(prefix);    lua_pushstring(luaState, word.c_str());    return 1;//目标函数返回值的个数}extern int luaopen_TestBind_luabinding(lua_State* luaState){    int top = lua_gettop(luaState);        static const struct luaL_Reg funcs[] = {        {"sayHelo", TestBind_getWorld},        {NULL, NULL}    };    luaL_register(luaState, BIND_PREFIX.c_str(), funcs);//BIND_PREFIX 指的是函数所属的全局表    lua_settop(luaState, top);}

最后,将绑定函数在AppDelegate中注册一下:

 1 #include "CCLuaEngine.h" 2 #include "SimpleAudioEngine.h" 3 #include "TestBind_luabinding.h" 4  5 bool luaBinding(lua_State* luaState){ 6     lua_CFunction luabinds[] = { 7         luaopen_TestBind_luabinding, 8         nullptr 9     };10     loadlibs(luabinds, luaState);11     return true;12 }13 14 bool AppDelegate::applicationDidFinishLaunching()15 {16     auto engine = LuaEngine::getInstance();17     ScriptEngineManager::getInstance()->setScriptEngine(engine);18     19     lua_State *luaState = engine->getLuaStack()->getLuaState();20     21     //注册lua-binding函数22     if (!luaBinding(luaState)) {23         CCLOG("Launch # register lua-binding error");24         return false;25     }26 //    engine->executeString("print(‘this is a executeString!‘)");27     28     if (engine->executeScriptFile("src/main.lua")) {29         return false;30     }31     32     33     34 35     return true;36 }

 

关于在Cocos2dx引擎中手动绑定C++到Lua