当前位置: 首页 > news >正文

C/C++ 与 Lua 互相调用详解

        Lua 是一门轻量级、嵌入式的脚本语言,常常与 C/C++ 结合使用。通过嵌入 Lua,可以让应用程序获得灵活的配置、脚本化逻辑和可扩展性。

         本文将介绍如何在 C/C++ 调用 Lua 函数,以及如何让 Lua 调用 C/C++ 函数。最后给出一个 完整的示例工程,可以直接编译运行。


一、C 调用 Lua

Lua 脚本(script.lua):

-- 定义一个 Lua 函数
function add(a, b)return a + b
end

C++ 代码调用:

lua_getglobal(L, "add");   // 获取 Lua 中的函数
lua_pushnumber(L, 10);     // 压入参数
lua_pushnumber(L, 20);if (lua_pcall(L, 2, 1, 0) != 0) {std::cerr << "Error: " << lua_tostring(L, -1) << std::endl;
}double result = lua_tonumber(L, -1); // 获取返回值
lua_pop(L, 1);                       // 弹出栈顶

运行后会输出 30


二、Lua 调用 C/C++

Lua 可以调用在 C/C++ 里注册的函数。

C++ 代码:

int cpp_multiply(lua_State* L) {int a = luaL_checkinteger(L, 1);int b = luaL_checkinteger(L, 2);lua_pushinteger(L, a * b);return 1; // 返回值数量
}

注册函数:

lua_register(L, "cpp_multiply", cpp_multiply);

Lua 调用:

print("cpp_multiply result:", cpp_multiply(6, 7))

运行后会输出 42


三、完整示例工程

目录结构

demo-lua/
├── CMakeLists.txt
├── main.cpp
└── script.lua


1. CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(demo-lua CXX)set(CMAKE_CXX_STANDARD 11)# 查找 Lua
find_package(PkgConfig REQUIRED)
pkg_search_module(LUA REQUIRED lua5.3)include_directories(${LUA_INCLUDE_DIRS})
link_directories(${LUA_LIBRARY_DIRS})add_executable(demo main.cpp)
target_link_libraries(demo ${LUA_LIBRARIES})

2. script.lua

-- Lua 脚本文件-- 定义函数
function add(a, b)return a + b
end-- 调用 C++ 注册的函数
function test_cpp_func()local res = cpp_multiply(6, 7)print("cpp_multiply result from Lua:", res)
end

3. main.cpp

#include <iostream>
#include <lua.hpp>// C++ 函数:在 Lua 中注册为 cpp_multiply
int cpp_multiply(lua_State* L) {int a = luaL_checkinteger(L, 1);int b = luaL_checkinteger(L, 2);lua_pushinteger(L, a * b);return 1;
}int main() {lua_State* L = luaL_newstate();   // 创建 Lua 虚拟机luaL_openlibs(L);                 // 打开标准库// 注册 C++ 函数到 Lualua_register(L, "cpp_multiply", cpp_multiply);// 加载 Lua 脚本if (luaL_dofile(L, "script.lua")) {std::cerr << "Failed to load script.lua: "<< lua_tostring(L, -1) << std::endl;lua_close(L);return 1;}// 调用 Lua 的 add() 函数lua_getglobal(L, "add");lua_pushnumber(L, 10);lua_pushnumber(L, 20);if (lua_pcall(L, 2, 1, 0) != 0) {std::cerr << "Error running add(): "<< lua_tostring(L, -1) << std::endl;lua_close(L);return 1;}double result = lua_tonumber(L, -1);lua_pop(L, 1);std::cout << "Result from Lua add(): " << result << std::endl;// 调用 Lua 的 test_cpp_func()lua_getglobal(L, "test_cpp_func");if (lua_pcall(L, 0, 0, 0) != 0) {std::cerr << "Error running test_cpp_func(): "<< lua_tostring(L, -1) << std::endl;}lua_close(L);return 0;
}

四、构建与运行

# 编译
mkdir build && cd build
cmake ..
make# 运行
./demo


五、运行效果


http://www.xdnf.cn/news/1466767.html

相关文章:

  • SpringMVC(一)
  • 混合架构大型语言模型(Jamba)
  • 当低代码遇上AI,有趣,实在有趣
  • WebRTC进阶--WebRTC错误Failed to unprotect SRTP packet, err=9
  • 【Flutter】drag_select_grid_view: ^0.6.2 使用
  • AI架构师的思维方式与架构设计原则
  • 【LeetCode - 每日1题】最少操作使num1归零
  • Bean作用域和生命周期
  • Golang中的context包介绍及源码阅读
  • 谙流 ASK 技术解析(一):秒级扩容
  • Android,jetpack Compose模仿QQ侧边栏
  • 华为云昇腾云服务
  • 数据安全成焦点:基于Hadoop+Spark的信用卡诈骗分析系统实战教程
  • 为什么外网主机可以telnet通内网nginx端口,但是http请求失败?
  • Mysql:由逗号分隔的id组成的varchar联表替换成对应文字
  • Tenda AC20路由器缓冲区溢出漏洞分析
  • iOS 抓包工具有哪些?开发、测试与安全场景的实战选择
  • 软考 系统架构设计师系列知识点之杂项集萃(140)
  • 使用 chromedp 高效爬取 Bing 搜索结果
  • 安装Codex(需要用npm)
  • Chrome 插件开发入门指南:从基础到实践
  • 达梦数据守护集群监视器详解与应用指南
  • vsan高可用:确保可访问性、全部数据迁移,两种类型权衡
  • 软件启动时加配置文件 vs 不加配置文件
  • Go 1.25.1基本包
  • 凌力尔特(LINEAR)滤波器LTC1068的二阶滤波器模块设计
  • STM32 USBx Device HID standalone 移植示例 LAT1466
  • 全球企业内容管理ECM市场规模增长趋势与未来机遇解析
  • (4)什么时候引入Seata‘‘
  • 黄金上门回收小程序开发