用LUA做程序配置文件
本来想用bison、flex来写一个配置文件的。但是看了看资料,不容易懂,而且也不灵活。还是放弃了。
后来想起了lua,现在流行用lua来做服务程序的配置文件。强大、灵活,而且与C可以紧密结合。
下面是C程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | /* * getcfg.c * cc -o getcfg getcfg.c -I/usr/local/include/lua51 -L/usr/local/lib/lua51 -llua -lm */ #include <lua.h> #include <lauxlib.h> #include <stdlib.h> #include <stdio.h> int main(void) { int status, result, ind; const char *key, *value; double sum; lua_State *L; /* * All Lua contexts are held in this structure. We work with it almost * all the time. */ L = luaL_newstate(); luaL_openlibs(L); /* Load Lua libraries */ /* Load the file containing the script we are going to run */ if ( luaL_loadfile(L, "server.cfg") || lua_pcall(L, 0, 0, 0) ) { /* If something went wrong, error message is at the top of */ /* the stack */ fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1)); lua_pop(L, 1); exit(1); } lua_getglobal(L, "socket" ); const char *socket = lua_tostring(L, -1); printf( "socket %s\n", lua_tostring(L, -1)); lua_pop(L, 2); lua_getglobal(L, "servers"); if (!lua_istable(L, -1)) { fprintf(stderr, "%s\n", lua_tostring(L, -1)); lua_pop(L, 1); // remove the error-msg return -1; } ind = lua_gettop(L); printf( "index: %d\n", ind ); lua_pushnil(L); while (lua_next(L, -2) != 0) { /** 获取服务索引名 */ key = lua_tostring(L, -2); printf( "key name: %s\n", key ); if (lua_istable(L, -1)) { ind = 1; lua_pushnil(L); while (lua_next(L, -2) != 0) { /** 获取服务配置 */ key = lua_tostring(L, -2); if(strcmp("bin", key) == 0) { printf( "bin %s\n", lua_tostring(L, -1) ); } else if(strcmp("pid", key) == 0) { printf( "pid %s\n", lua_tostring(L, -1) ); } else if(strcmp("params", key) == 0) { printf( "params %s\n", lua_tostring(L, -1) ); } else if(strcmp("config", key) == 0) { printf( "config %s\n", lua_tostring(L, -1) ); } else { printf("Unkonw key: %s\n", key ); } lua_pop( L, 1 ); } } lua_pop(L, 1); } lua_close(L); /* Cya, Lua */ return 0; } |
下面是LUA代码:
1 2 3 4 5 6 7 8 9 10 11 12 | daemon = false socket = "/var/run/daemon-server.sock" servers = { ["phpd"] = { pid = "/var/run/phpd.pid", bin = "/usr/local/sbin/phpd", delay = 300, } } |




最新评论