sol2和LuaBridge是C++集成Lua的两大主流绑定库:sol2功能全、现代易用,适合中大型项目;LuaBridge极简零开销,适合资源受限场景。

在 C++ 项目中集成 Lua 是提升扩展性与热更新能力的常用手段,sol2 和 LuaBridge 是目前最主流的两个轻量、现代、易用的绑定库。它们都基于 Lua C API,但大幅简化了类型映射、函数注册和对象生命周期管理。核心目标不是“让 Lua 跑起来”,而是“让 C++ 和 Lua 自然地互相调用、共享数据、协同工作”。
两者都支持 C++14+,无需预编译或代码生成,头文件即用(header-only),无额外依赖。区别在于设计哲学:
只需引入 sol.hpp(单头文件),确保链接 lua5.4(或对应版本)库:
#include <sol/sol.hpp>
#include <iostream>
<p>int add(int a, int b) { return a + b; }</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/6e7abc4abb9f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">C++免费学习笔记(深入)</a>”;</p><p>struct Vec2 {
float x = 0, y = 0;
Vec2(float x<em>, float y</em>) : x(x<em>), y(y</em>) {}
float len() const { return std::sqrt(x<em>x + y</em>y); }
};</p><p>int main() {
sol::state lua;
lua.open_libraries(); // 启用标准库(base, table, string...)</p><pre class="brush:php;toolbar:false;">// 暴露普通函数
lua.set_function("add", add);
// 暴露类(自动处理构造、成员函数、属性)
lua.new_usertype<Vec2>("Vec2",
sol::constructors<Vec2(float, float)>(),
"x", &Vec2::x,
"y", &Vec2::y,
"len", &Vec2::len
);
// 执行 Lua 脚本
lua.script(R"(
local v = Vec2(3, 4)
print("length:", v:len()) -- 输出: length: 5
print("sum:", add(10, 20)) -- 输出: sum: 30
)");
return 0;}
引入 LuaBridge.h,不依赖 STL 模板实例化,适合资源受限环境:
#include "LuaBridge/LuaBridge.h"
#include <iostream>
<p>int multiply(int a, int b) { return a * b; }</p><p>struct Point {
int x, y;
Point(int x<em> = 0, int y</em> = 0) : x(x<em>), y(y</em>) {}
int dist() { return x<em>x + y</em>y; }
};</p><p>int main() {
lua_State* L = luaL_newstate();
luaL_openlibs(L);</p><pre class="brush:php;toolbar:false;">// 注册全局函数
luabridge::getGlobalNamespace(L)
.addFunction("multiply", multiply)
// 注册类(需手动指定构造器、方法、属性)
.beginClass<Point>("Point")
.addConstructor<void(*) (int, int)>()
.addProperty("x", &Point::x)
.addProperty("y", &Point::y)
.addFunction("dist", &Point::dist)
.endClass();
lua_dostring(L, R"(
local p = Point(3, 4)
print('dist:', p:dist()) -- 输出: dist: 25
print('mul:', multiply(6, 7)) -- 输出: mul: 42
)");
lua_close(L);
return 0;}
真正发挥 Lua 的扩展价值,不能只停留在“能调用”,而要构建可持续维护的脚本架构:
require 拆分逻辑(如 ai.lua、ui.lua),C++ 层统一管理模块搜索路径(package.path)。os.execute, io.open),重定向 print 到日志系统,设置最大执行指令数(lua_sethook)防死循环。sol::protected_function_result,LuaBridge 用 lua_pcall,避免未处理异常导致 C++ 崩溃。ffi 或自定义 lightuserdata 封装),避免序列化开销。基本上就这些。sol2 更省心,LuaBridge 更透明——选哪个取决于你更在意开发效率,还是运行时确定性。两者都不复杂,但容易忽略错误处理和模块隔离,而这恰恰是长期扩展性的分水岭。
以上就是c++++如何集成Lua脚本引擎_c++ sol2/LuaBridge使用教程【扩展性】的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号