使用Lua作為C語言項目的配置文件實例
想像一個場景:你的c程序需要有一個窗口,你想讓用戶可以自定義窗口大小。方法很多,比如使用環(huán)境變量,或鍵值對的文件。不管怎樣,你需要解析它。使用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為你處理了所有語法細節(jié)(包括錯誤)
2.配置內容可讀性好,甚至你可以寫上注釋。
3.可以很容易添加新的配置信息。
(完)