uci/lua: add explicit close() method
[project/uci.git] / lua / uci.c
index 8ace746..22055cb 100644 (file)
--- a/lua/uci.c
+++ b/lua/uci.c
@@ -113,11 +113,8 @@ find_package(lua_State *L, struct uci_context *ctx, const char *str, bool al)
                goto done;
        }
 
-       if (al == true)
+       if (al)
                uci_load(ctx, name, &p);
-       else if (al) {
-               uci_load(ctx, name, &p);
-       }
 
 done:
        if (name != str)
@@ -303,7 +300,7 @@ uci_lua_foreach(lua_State *L)
        ctx = find_context(L, &offset);
        package = luaL_checkstring(L, 1 + offset);
 
-       if (lua_isnil(L, 2))
+       if (lua_isnil(L, 2 + offset))
                type = NULL;
        else
                type = luaL_checkstring(L, 2 + offset);
@@ -914,10 +911,41 @@ uci_lua_set_savedir(lua_State *L)
 }
 
 static int
+uci_lua_list_configs(lua_State *L)
+{
+       struct uci_context *ctx;
+       char **configs = NULL;
+       char **ptr;
+       int i = 1;
+
+       ctx = find_context(L, NULL);
+       if ((uci_list_configs(ctx, &configs) != UCI_OK) || !configs)
+               return uci_push_status(L, ctx, false);
+       lua_newtable(L);
+       for (ptr = configs; *ptr; ptr++) {
+               lua_pushstring(L, *ptr);
+               lua_rawseti(L, -2, i++);
+       }
+       free(configs);
+       return 1;
+}
+
+static int
 uci_lua_gc(lua_State *L)
 {
-       struct uci_context *ctx = find_context(L, NULL);
-       uci_free_context(ctx);
+       struct uci_context **ctx;
+
+       if (!lua_isuserdata(L, 1)) {
+               if (!global_ctx)
+                       return 0;
+               ctx = &global_ctx;
+       } else {
+               ctx = luaL_checkudata(L, 1, METANAME);
+               if (!*ctx)
+                       return 0;
+       }
+       uci_free_context(*ctx);
+       *ctx = NULL;
        return 0;
 }
 
@@ -953,6 +981,7 @@ uci_lua_cursor(lua_State *L)
 
 static const luaL_Reg uci[] = {
        { "__gc", uci_lua_gc },
+       { "close", uci_lua_gc },
        { "cursor", uci_lua_cursor },
        { "load", uci_lua_load },
        { "unload", uci_lua_unload },
@@ -974,6 +1003,7 @@ static const luaL_Reg uci[] = {
        { "set_confdir", uci_lua_set_confdir },
        { "get_savedir", uci_lua_get_savedir },
        { "set_savedir", uci_lua_set_savedir },
+       { "list_configs", uci_lua_list_configs },
        { NULL, NULL },
 };
 
@@ -994,8 +1024,9 @@ luaopen_uci(lua_State *L)
 
        /* create module */
        lua_newtable(L);
+       lua_pushvalue(L, -1);
        luaL_setfuncs(L, uci, 0);
        lua_setglobal(L, MODNAME);
 
-       return 0;
+       return 1;
 }