C++嵌入Lua读取配置文件
这段时间一直在写工具,遇到一些问题,Google下解决了,这里想把解决问题的成果提取出来分享下,也方便我以后使用,^_^
写工具就应该尽量的灵活,可配置性强,配置文件是少不了的。
之前用过自定义配置文件(我的另一篇文章中提到过:http://www.cnblogs.com/MikeZhang/archive/2011/11/19/2255169.html),灵活是灵活,可写起来有点麻烦,而且如果想把部分逻辑写在外面,在配置文件中弄个函数就很不随意了——自己要写个脚本引擎进行解析……
最后决定用lua作为配置文件的解析器,这里有个简单的demo:
1 /*
2 File : demo.cpp
3 Author : Mike
4 E-Mail : Mike_Zhang@live.com
5 */
6 #include <stdio.h>
7 extern "C"
8 {
9 #include "lua.h"
10 #include "lualib.h"
11 #include "lauxlib.h"
12 }
13
14 lua_State *L;
15 const char *lua_Script = "function add(a, b) return (a+b) end ";
16
17 int lua_add(lua_State *L, const char *fun_name, int x, int y)
18 {
19 int ret;
20 lua_getglobal(L, fun_name);
21 lua_pushnumber(L, x);
22 lua_pushnumber(L, y);
23 lua_call(L, 2, 1);
24 ret = (int)lua_tointeger(L, -1);
25 lua_pop(L, 1);
26 return ret;
27 }
28
29 int test()
30 {
31 int ret = 0;
32 lua_State *L = lua_open(); /* opens Lua */
33 luaL_openlibs(L);
34 if (luaL_dostring(L, lua_Script)) // Run lua script
35 {
36 printf("error!\n");
37 lua_close(L);
38 return -1;
39 }
40 ret = lua_add(L, "add", 4, 5);
41 printf("%d\n",ret);
42 lua_close(L);
43 return 0;
44 }
45
46 int main()
47 {
48 test();
49 return 0;
50 }
另外,我自己写了个C++调用Lua的类,感兴趣的话,可以到这里去找:
项目地址:http://sourceforge.net/projects/cppcalllua/
svn访问:svn checkout http://svn.code.sf.net/p/cppcalllua/code-0/trunk cppcalllua-code-0
Tips : 这是一个CodeBlocks的工程,工程文件 : CppCallLua.cbp
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)