From aac519b946627d23b4e923eb542dcab68cbd50ec Mon Sep 17 00:00:00 2001 From: Uli Schlachter Date: Sat, 12 Aug 2017 16:32:27 +0200 Subject: [PATCH] Refactor spawn.c This moves some code of parse_command() out into a new helper function. No functional changes intended. Signed-off-by: Uli Schlachter --- spawn.c | 69 +++++++++++++++++++++++++++++++++++---------------------- 1 file changed, 43 insertions(+), 26 deletions(-) diff --git a/spawn.c b/spawn.c index 01f8662f9..b025ab2bf 100644 --- a/spawn.c +++ b/spawn.c @@ -369,6 +369,48 @@ spawn_callback(gpointer user_data) unsetenv("DESKTOP_STARTUP_ID"); } +/** Convert a Lua table of string to a char** array. + * \param L The Lua VM state. + * \param idx The index of the table that we should parse + * \return The argv array. + */ +static gchar ** +parse_table_array(lua_State *L, int idx, GError **error) +{ + gchar **argv = NULL; + size_t i, len; + + luaL_checktype(L, idx, LUA_TTABLE); + idx = luaA_absindex(L, idx); + len = luaA_rawlen(L, idx); + + /* First verify that the table is sane: All integer keys must contain + * strings. Do this by pushing them all onto the stack. + */ + for (i = 0; i < len; i++) + { + lua_rawgeti(L, idx, i+1); + if (lua_type(L, -1) != LUA_TSTRING) + { + g_set_error(error, G_SPAWN_ERROR, 0, + "Non-string argument at table index %zd", i+1); + return NULL; + } + } + + /* From this point on nothing can go wrong and so we can safely allocate + * memory. + */ + argv = g_new0(gchar *, len + 1); + for (i = 0; i < len; i++) + { + argv[len - i - 1] = g_strdup(lua_tostring(L, -1)); + lua_pop(L, 1); + } + + return argv; +} + /** Parse a command line. * \param L The Lua VM state. * \param idx The index of the argument that we should parse @@ -378,7 +420,6 @@ static gchar ** parse_command(lua_State *L, int idx, GError **error) { gchar **argv = NULL; - idx = luaA_absindex(L, idx); if (lua_isstring(L, idx)) { @@ -388,31 +429,7 @@ parse_command(lua_State *L, int idx, GError **error) } else if (lua_istable(L, idx)) { - size_t i, len = luaA_rawlen(L, idx); - - /* First verify that the table is sane: All integer keys must contain - * strings. Do this by pushing them all onto the stack. - */ - for (i = 0; i < len; i++) - { - lua_rawgeti(L, idx, i+1); - if (lua_type(L, -1) != LUA_TSTRING) - { - g_set_error(error, G_SPAWN_ERROR, 0, - "Non-string argument at table index %zd", i+1); - return NULL; - } - } - - /* From this point on nothing can go wrong and so we can safely allocate - * memory. - */ - argv = g_new0(gchar *, len + 1); - for (i = 0; i < len; i++) - { - argv[len - i - 1] = g_strdup(lua_tostring(L, -1)); - lua_pop(L, 1); - } + argv = parse_table_array(L, idx, error); } else {