LuaBridge : 连接你的C++和Lua

Lua 和 C++ 交互的的库很多,常见的有LuaWrapper,tolua++, luabind等等,以前实用LuaWrapper后来发现了LuaBridge,一个十分轻量级的库,正如它的介绍一样:

LuaBridge is a lightweight and dependency-free library for mapping data, functions, and classes back and forth between C++ and Lua (a powerful, fast, lightweight, embeddable scripting language) .

事实上,它轻到只有17个.h的头文件!但这足以完成大部分的功能。

可以这样简单的使用它

int main(){

    L = luaL_newstate();//创建lua环境
    luaL_openlibs(L);
   

    using namespace luabridge;
    getGlobalNamespace(L)
        .beginNamespace("Test")
        .addFunction("SayHello", &SayHello)//注册C++ 函数供lua调用
        .endNamespace()
    .endNamespace();

    luaL_dofile("Test.lua");

    luabridge::LuaRef refTest = getGlobal(L, "printstring"); //C++ 调用lua函数 printstring
    refTest("C++ Call Lua");

    lua_close(L);

}
void SayHello(const char* x) {
    printf("Lua Call C++ :%s\n", x);
}

 

 Test.lua如下

 

local SayHello= Test.SayHello
SayHello("luaBridge: lua call C++") --Lua call C++

function printstring(str)  -- Lua function for C++
    print(str)                                                                                                                                                                                               
end   

                                                                                                                                                                         

最简单的使用基本就这样,其实,luaBridge 还可以注册C++的类及成员函数等一些高级的数据结构,先写这些

参考:

https://github.com/vinniefalco/LuaBridge