c/c++解析lua配置文件
2013-08-15 19:11
477 查看
c/c++解析lua配置文件
lua是一个开源的可嵌入脚本语言,他的官方网站 http://www.lua.org/
lua脚本除了可以用来执行外,还可以做为配置文件,同时用C API来解析。比如在游戏里比较常见。
在 C/C++中解析lua有以下步骤如下:
1. 包含lua头文件,如果是C++程序,需要声明 extern c
2. 创建lua_State, 打开lua标准库
3. 载入和运行lua配置文件
4. 读取配置文件内容。 lua跟C/C++的数据交换通过栈来进行。C/C++ 通过lua的API函数从lua_State中读取数据并压入栈中,然后再读取栈中的数据, 最后再把数据从栈中pop出来.
如果lua配置文件里的数据是嵌套定义的, 那么就需要嵌套执行上面的程序段,把数据读出来.
如果是有很多相同类型的数据集合,就需要不断把数据压入栈中读取, 比如:
lua是一个开源的可嵌入脚本语言,他的官方网站 http://www.lua.org/
lua脚本除了可以用来执行外,还可以做为配置文件,同时用C API来解析。比如在游戏里比较常见。
在 C/C++中解析lua有以下步骤如下:
1. 包含lua头文件,如果是C++程序,需要声明 extern c
1 extern C 2 { 3 #include "lua.h" 4 #include "lualib.h" 5 #include "lauxlib.h" 6 };
2. 创建lua_State, 打开lua标准库
1 lua_State* L = luaL_newstate(); 2 luaL_openlibs(L);
3. 载入和运行lua配置文件
1 luaL_loadfile(L, "scene.lua"); 2 lua_pcall(L, 0, LUA_MULTRET, 0); 3 4 //或者直接调用lua_dofile来完成载入和运行 5 //luaL_dofile(L, "scene.lua");
4. 读取配置文件内容。 lua跟C/C++的数据交换通过栈来进行。C/C++ 通过lua的API函数从lua_State中读取数据并压入栈中,然后再读取栈中的数据, 最后再把数据从栈中pop出来.
1 lua_getfeild(L,idx, key); //push t[k] onto the stack, where t is the value at the given valid index 2 3 // or get the global value and push it on to the stack, as below 4 // lua_getglobal(L, key); // push onto the stack the value of the global key 5 6 // read data from the stack 7 const char* str = lua_tostring(L,-1); 8 //or 9 // int b = lua_toboolean(L,-1); 10 //or other data types 11 // ... 12 13 lua_pop(L, 1);
如果lua配置文件里的数据是嵌套定义的, 那么就需要嵌套执行上面的程序段,把数据读出来.
如果是有很多相同类型的数据集合,就需要不断把数据压入栈中读取, 比如:
1 lua_pushnil(L); 2 while(lua_next(L, -2)) 3 { 4 lua_getfeild(L, -1, key); 5 6 // read data from the stack 7 const char* str = lua_tostring(L,-1); 8 //or 9 // int b = lua_toboolean(L,-1); 10 //or other data types 11 // ... 12 13 lua_pop(L, 1); 14 }
相关文章推荐
- c/c++解析lua配置文件
- LUA解析配置文件 简单实例
- 如何用C++解析配置文件
- C++中调用Lua配置文件和响应函数示例
- sublime搭建c++/java/lua/python/ruby的配置文件
- C++嵌入Lua读取配置文件
- cocos2dx lua解析csv成lua配置文件,方便程序调用
- vs2013 c++ 编译配置jsoncpp和使用jsoncpp解析json文件
- C++解析json文件-VS2010中配置Jsoncpp
- C/C++ 中使用lua作为配置文件
- C++实现解析INI配置文件
- LUA解析配置文件-C语言调用
- 关于C++读取Lua配置文件实现案例
- C++ hash_map简单应用之解析配置文件
- lua 与 c/c++ 交互(4)将lua作为一种配置文件
- C++嵌入Lua读取配置文件
- C++调用Lua读取配置文件的一个简单例子
- c/c++ 简单的解析ini配置文件程序
- c、c++获取lua脚本里面定义的table可做配置文件用
- INI配置文件解析——C++实现