Lua,Lua API,配置文件

想像一个场景:你的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.能够非常easy加入新的配置信息。

(完)