uci/lua: add explicit close() method
[project/uci.git] / lua / uci.c
index 1cb31a594c7823144dd5200c7656b38c4ea4d65b..22055cb7e367e3db3f459a7604de4c7f83559baf 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)
@@ -913,11 +910,42 @@ uci_lua_set_savedir(lua_State *L)
        return uci_push_status(L, ctx, false);
 }
 
+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 },
 };