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

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

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

--define window size
width = 100
height = 50

然后,我们写个函数来解析它,使用lua API 来指导lua解析配置。,下面是完整的程序:
#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

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配置文件有什么好处呢?我想,大概有以下理由:
1.Lua为你处理了所有语法细节(包括错误)
2.配置内容可读性好,甚至你可以写上注释。
3.可以很容易添加新的配置信息。
(完)