使用Lua作为C语言项目的配置文件实例

这篇文章主要介绍了使用Lua作为C语言项目的配置文件实例,本文用Lua创建了一个配置文件,然后在C言语中解析它,需要的朋友可以参考下

想像一个场景:你的c程序需要有一个窗口,你想让用户可以自定义窗口大小。方法很多,比如使用环境变量,或键值对的文件。不管怎样,你需要解析它。使用lua配置文件是个不错的选择。

首先,你可以定义如下的配置文件:

复制代码 代码如下:

--define window size
width = 100
height = 50

然后,我们写个函数来解析它,使用lua API 来指导lua解析配置。,下面是完整的程序:
复制代码 代码如下:

#include
#include
#include
#include
#include

void load(lua_State* L, const char* fname, int *w, int *h)
{
     if (luaL_loadfile(L, fname) || lua_pcall(L, 0, 0, 0)) {
          error(L, "error:%s", lua_tostring(L, -1));
     }
     lua_getglobal(L, "width");
     lua_getglobal(L, "height");
     if (!lua_isnumber(L, -2)) {
          error(L, "width shuld be num.");
     }
     if (!lua_isnumber(L, -1)) {
          error(L, "height shuld be num");
     }
     *w = lua_tointeger(L, -2);
     *h = lua_tointeger(L, -1);
}

int main()
{
     lua_State *L = luaL_newstate();
     luaL_openlibs(L);
     int w, h;
     load(L, "config", &w, &h);
     printf("%d,%d", w, h);
     return 0;
}

以上就是使用Lua作为C语言项目的配置文件实例的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Lua