summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorsanine-a <sanine.not@pm.me>2020-12-12 22:12:36 -0600
committersanine-a <sanine.not@pm.me>2020-12-12 22:12:36 -0600
commite523415348450207832e76363d83048c6f06ad1e (patch)
tree7faa1124fe4ddcdc208f47aa86146ab2c9913d7a
parent09d34c697a488a8450161c62a601b04748098d96 (diff)
add param table parsing function
-rw-r--r--src/common.h21
-rw-r--r--src/honey_lua.c26
2 files changed, 47 insertions, 0 deletions
diff --git a/src/common.h b/src/common.h
index cb0ba45..03d6944 100644
--- a/src/common.h
+++ b/src/common.h
@@ -153,6 +153,27 @@ typedef enum {
*/
int honey_lua_parse_arguments(lua_State* L, unsigned int n, ...);
+/** @brief Process a param table.
+ *
+ * Please ensure that the param table is on top of the stack before calling this function.
+ *
+ * The first m elements of the param table are required, and their absence from
+ * the table will trigger an error.
+ *
+ * The variadic portion of this function expects arguments as
+ * param_name_1, function1, (void*) data1, param_name_2, function_2, (void*) data_2, ...
+ *
+ * Each function should be of the form void (*)(lua_State*, void*)
+ *
+ * @param[in] L The lua state to parse the table from.
+ * @param[in] n The number of params to parse.
+ * @param[in] m The number of required params.
+ * @param[inout] ... Variadic list of param processing functions, as described above.
+ *
+ * @returns Nothing, but throws a lua error if a required argument is not found.
+ */
+void honey_lua_parse_params(lua_State* L, int n, int m, ...);
+
/** @brief Wrap C objects for lua. */
typedef struct honey_lua_element {
char* name;
diff --git a/src/honey_lua.c b/src/honey_lua.c
index f3ca0a5..ff1d82d 100644
--- a/src/honey_lua.c
+++ b/src/honey_lua.c
@@ -247,6 +247,32 @@ int honey_lua_parse_arguments(lua_State* L, unsigned int n, ...)
return index;
}
+/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
+
+void honey_lua_parse_params(lua_State* L, int n, int m, ...)
+{
+ int table_index = lua_gettop(L);
+
+ va_list args;
+ va_start(args, m);
+
+ for (int i=0; i<n; i++) {
+ const char* param = va_arg(args, const char*);
+ void (*function)(lua_State*, void*) = va_arg(args, void (*)(lua_State*, void*));
+ void* data = va_arg(args, void*);
+
+ lua_getfield(L, table_index, param);
+ if (lua_isnil(L, -1) && n < m)
+ honey_lua_throw_error
+ (L, "required parameter '%s' was not found in param table!", param);
+
+ function(L, data);
+ lua_pop(L, 1);
+ }
+
+ va_end(args);
+}
+
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Table creation functions