From 78d83c1c4ae765636584616b99ccf146636669cf Mon Sep 17 00:00:00 2001 From: ame Date: Thu, 11 Jan 2024 08:54:58 -0600 Subject: arg_handle --- docs/io.md | 28 ++++++++++++++++++++++++++++ src/io.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ src/io.h | 2 ++ 3 files changed, 74 insertions(+) diff --git a/docs/io.md b/docs/io.md index dd5aff0..79b4b23 100644 --- a/docs/io.md +++ b/docs/io.md @@ -52,3 +52,31 @@ returns a table represented by the string ```lua llib.io.json_parse('{"test":[5,4,3]}') -- {"test" : {5, 4, 3}} ``` + +### arg_handle + +'accepts two tables + 1 = table mapped with names and function + 2 = args, or the list of strings to test + +the first table accepts this layout + +{ { list_of_keys, function_to_execute }, ... } + +returns nothing, executes marked functions + +```lua +llib.io.arg_handle({ + { + {"test"}, + function() + print("test") + end, + }, { + {"test2","t"}, + function() + print("test2") + end, + } +}, arg) +``` diff --git a/src/io.c b/src/io.c index f30f867..10fe048 100644 --- a/src/io.c +++ b/src/io.c @@ -246,5 +246,49 @@ void json_parse(lua_State* L, str* raw){ int l_json_parse(lua_State* L){ str* raw_json = str_init((char*)luaL_checklstring(L, 1, NULL)); json_parse(L, raw_json); + str_free(raw_json); return 1; } + +int l_arg_handle(lua_State* L){ + luaL_checktype(L, 1, LUA_TTABLE); + luaL_checktype(L, 2, LUA_TTABLE); + + size_t len = lua_objlen(L,1); + for(size_t i = 0; i <= len - 1; i++){ + lua_pushnumber(L,i + 1); + lua_gettable(L,1); + + lua_pushnumber(L,1); + lua_gettable(L,-2); + size_t inner_len = lua_objlen(L,-1); + size_t inner_idx = lua_gettop(L); + + lua_pushnumber(L, 2); + lua_gettable(L, -3); + + size_t function_idx = lua_gettop(L); + + for(int ii = 1; ii <= inner_len; ii++){ + lua_pushnumber(L, ii); + lua_gettable(L, inner_idx); + + const char* key = lua_tostring(L, -1); + + size_t input_len = lua_objlen(L, 2); + + for(int iii = 1; iii <= input_len; iii++){ + lua_pushnumber(L, iii); + lua_gettable(L, 2); + if(strcmp(lua_tostring(L, -1), key) == 0){ + lua_pushvalue(L, function_idx); + lua_pcall(L, 0, 0, 0); + ii = inner_len + 1; + break; + } + } + + } + } + return 0; +} diff --git a/src/io.h b/src/io.h index 570e4b4..21e14d0 100644 --- a/src/io.h +++ b/src/io.h @@ -24,6 +24,7 @@ int l_log(lua_State*); int l_warn(lua_State*); int l_error(lua_State*); int l_pprint(lua_State*); +int l_arg_handle(lua_State*); int l_json_parse(lua_State*); @@ -35,5 +36,6 @@ static const luaL_Reg io_function_list [] = { {"error",l_error}, {"pprint",l_pprint}, {"json_parse",l_json_parse}, + {"arg_handle",l_arg_handle}, {NULL,NULL} }; -- cgit v1.2.3