C++中调用Lua配置文件和响应函数示例
Lua作为轻量级脚本语言,无需编译即可实现热更新。C++通过lua_getglobal和lua_pcall等API获取Lua全局变量、调用函数并处理返回值,核心在于理解Lua栈的压栈、出栈与类型检查操作,适用于配置分离与业务逻辑热更新场景。
Lua 作为一门轻量级脚本语言,最大的优势就在于它的灵巧与便捷——无需编译,随改随用。当 C/C++ 的底层框架搭建完成后,只需要更改 Lua 脚本中的对应逻辑,就能调整功能,而完全不需要重新编译整个工程。这种“热更新”能力在实际项目中非常实用。下面就用一个完整的示例,演示如何在 C 中调用 Lua 配置文件和响应函数。
C++ 端代码如下:

// Lua1.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #includeextern "C" { // 如果不加 extern "C",会因为编译成 C++ 文件而导致链接错误 #include #include #include } void load (lua_State *L,int *width,int *height){ lua_getglobal(L,"width"); // 获取 Lua 中变量的值,将其压入栈 lua_getglobal(L,"height"); if(!lua_isnumber(L,-2)) // 栈顶为 -1,依次递减 luaL_error(L,"`width' should be a numbern"); if(!lua_isnumber(L,-1)) luaL_error(L,"`height' should be a numbern"); *width = (int)lua_tonumber(L,-2); // 将栈顶元素转为数字 *height = (int)lua_tonumber(L,-1); } int add(lua_State *L,int a, int b){ int sum=0; lua_getglobal(L,"add"); // 函数也是变量,因此用同样的方式获取 lua_pushnumber(L,a); // 传入参数 lua_pushnumber(L,b); // 第二个参数为调用函数的参数个数,第三个为返回值个数,第四个为错误处理函数,正常运行返回 0 if(lua_pcall(L,2,1,0) != 0){ luaL_error(L,"the lua load error! %s",lua_tostring(L,-1)); } // 函数的返回值已压入栈 if(!lua_isnumber(L,-1)){ luaL_error(L,"the func run error! %s",lua_tostring(L,-1)); } sum = (int)lua_tonumber(L,-1); // 取栈顶元素并转为数字,默认是 double 型 lua_pop(L,1) // 将 return 元素弹出 return sum; } int get_num(lua_State *L){ lua_getglobal(L,"roll_num"); if(lua_pcall(L,0,1,0) != 0){ luaL_error(L,"the lua load error! %s",lua_tostring(L,-1)); } if(!lua_isnumber(L,-1)){ luaL_error(L,"the func run error! %s",lua_tostring(L,-1)); } int n = (int)lua_tonumber(L,-1); lua_pop(L,1); return n; } int _tmain(int argc, _TCHAR* argv[]) { lua_State *L = lua_open(); luaL_openlibs(L); // 新版 Lua 库添加的方法 if(luaL_loadfile(L,"cof.lua") || lua_pcall(L,0,0,0)){ luaL_error(L,"loadfile error! %s n",lua_tostring(L,-1)); } int w=1,h=2; int sum; load(L,&w,&h); printf("width is %d ,height is %dn",w,h); sum=add(L,w,h); printf("the sum is: %d n",sum); bool flag = true; char c; while(flag){ printf("Do you want to roll the number? n"); scanf("%c",&c); if(c == 'y' || c=='Y'){ printf("rolling the number....n the num is %d n",get_num(L)); } else flag=false; getchar(); } getchar(); return 0; }
对应的 Lua 配置文件 cof.lua 内容如下:
-- config test width = 200 height = 500 function add(a,b) return a+b end math.randomseed(os.time()) function roll_num() return math.random(6) end
从示例中可以看到,C 端通过 lua_getglobal 和 lua_pcall 等 API,可以非常方便地获取 Lua 脚本中的全局变量、调用函数,并处理返回值。整个流程的核心就是理解 Lua 栈的操作:数据压栈、出栈、类型检查。实际开发中,这种模式非常适合用来实现配置分离、业务逻辑热更新等场景。代码虽然看起来有些“啰嗦”,但每一步都清晰可控,正是 Lua 与 C 交互的魅力所在。
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















