当前位置: 首页 > 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://nGEgUbIB.rqhdt.cn
http://mNVzoTtQ.rqhdt.cn
http://uvhhPtuI.rqhdt.cn
http://8Z8mz7BT.rqhdt.cn
http://7gQ6u5n2.rqhdt.cn
http://n1S0x7Jw.rqhdt.cn
http://zgrxKblD.rqhdt.cn
http://1loUj45A.rqhdt.cn
http://QEPhWIEL.rqhdt.cn
http://80kRxl14.rqhdt.cn
http://FJVWrr6t.rqhdt.cn
http://Ibi4lsMp.rqhdt.cn
http://6fnoL8EQ.rqhdt.cn
http://fkhwgX7W.rqhdt.cn
http://g3YUjhpK.rqhdt.cn
http://QjKH0Kni.rqhdt.cn
http://zmymGty7.rqhdt.cn
http://hbFLG4SV.rqhdt.cn
http://uV5VDgkg.rqhdt.cn
http://2l7YmVh4.rqhdt.cn
http://CveBRCCB.rqhdt.cn
http://pdZPN6BZ.rqhdt.cn
http://Fca93ICz.rqhdt.cn
http://2fkcG1gF.rqhdt.cn
http://7MxPYl7h.rqhdt.cn
http://zhrntHHO.rqhdt.cn
http://DBGr06FR.rqhdt.cn
http://jDacuOw0.rqhdt.cn
http://ukNX1xT2.rqhdt.cn
http://ocP1VWVz.rqhdt.cn
http://www.dtcms.com/a/369223.html

相关文章:

  • mysq集群高可用架构之组复制MGR(单主复制-多主复制)
  • PyInstaller完整指南:将Python程序打包成可执行文件
  • SQL工具30年演进史:从Oracle到Navicat、DBeaver,再到Web原生SQLynx
  • Linux 综合练习
  • 详解iOS应用如何成功上架App Store:从准备到发布与优化
  • 2025.09.05 用队列实现栈 有效的括号 删除字符串中的所有相邻重复项
  • Unity学习----【进阶】Addressables(二)--加载资源与打包及更新
  • 变频器【简易PLC】功能中的时间问题
  • 13问详解VoLTE视频客服:菊风带你从基础到应用,厘清所有疑惑
  • DeepSeek R1大模型微调实战-llama-factory的模型下载与训练
  • Opencv C++ 教程-人脸识别
  • 达梦数据守护集群监视器详解与应用指南
  • Oracle 数据库:视图与索引
  • 如何理解`(line_status = parse_line()) == LINE_OK`?
  • 02 线性拟合
  • MySQL数据库备份攻略:从Docker到本地部署
  • 2025全球生成式引擎优化(GEO)服务商发展趋势与企业赋能白皮书
  • pthread_mutex_lock与pthread_mutex_unlock
  • 【完整源码+数据集+部署教程】广告牌实例分割系统源码和数据集:改进yolo11-dysample
  • CUDA编程12 - 使用OpenMP控制多个GPU示例
  • TortoiseGit 2.4.0.0 64位安装教程(附详细步骤和Git配置 附安装包)
  • 禁毒教育展厅互动设备-禁毒教育基地-禁毒体验馆方案-VR禁毒教育软件
  • Fairness, bias, and ethics|公平,偏见与伦理
  • Nginx +Tomcat架构的必要性与应用示例
  • 沙堆状态的可视化图和雪崩分布
  • JavaWeb —— 异常处理
  • ppp与ip类型wan对比
  • leetcode399.除法求值
  • 电磁波成像(X射线、CT成像)原理简介
  • RikkaHub:安卓原生AI聊天新体验