注册 登录
编程论坛 C++教室

C++嵌入Lua读取配置文件

shitainong 发布于 2012-10-23 14:27, 403 次点击
这段时间一直在写工具,遇到一些问题,Google下解决了,这里想把解决问题的成果提取出来分享下,也方便我以后使用,^_^
写工具就应该尽量的灵活,可配置性强,配置文件是少不了的。
灵活是灵活,可写起来有点麻烦,而且如果想把部分逻辑写在外面,在配置文件中弄个函数就很不随意了——自己要写个脚本引擎进行解析……

最后决定用lua作为配置文件的解析器,这里有个简单的demo:


 1 /* 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 script35     {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的类,感兴趣的话,可以到这里去找:


svn访问:svn checkout http://svn.code. cppcalllua-code-0

Tips : 这是一个CodeBlocks的工程,工程文件 : CppCallLua.cbp
www.


[ 本帖最后由 shitainong 于 2012-10-23 14:30 编辑 ]
0 回复
1