aboutsummaryrefslogtreecommitdiffstats
path: root/src/lua
diff options
context:
space:
mode:
authorVsevolod Stakhov <vsevolod@highsecure.ru>2021-09-01 13:35:13 +0100
committerVsevolod Stakhov <vsevolod@highsecure.ru>2021-09-01 13:35:13 +0100
commit6b80e5120a9edeebee4e266fc17c81e2a5ddaf40 (patch)
treef4bd1e271977503db3a4292e201f332aa367ace4 /src/lua
parent760522c4da986f19e864da6123ba938f5e7d25d2 (diff)
downloadrspamd-6b80e5120a9edeebee4e266fc17c81e2a5ddaf40.tar.gz
rspamd-6b80e5120a9edeebee4e266fc17c81e2a5ddaf40.zip
[Minor] Add function to get a lua_reference from a string returning a function
Diffstat (limited to 'src/lua')
-rw-r--r--src/lua/lua_common.c50
-rw-r--r--src/lua/lua_common.h9
2 files changed, 59 insertions, 0 deletions
diff --git a/src/lua/lua_common.c b/src/lua/lua_common.c
index 06720c9f2..5d874d507 100644
--- a/src/lua/lua_common.c
+++ b/src/lua/lua_common.c
@@ -2292,6 +2292,56 @@ rspamd_lua_require_function (lua_State *L, const gchar *modname,
return FALSE;
}
+gint
+rspamd_lua_function_ref_from_str (lua_State *L, const gchar *str, gsize slen,
+ GError **err)
+{
+ gint err_idx, ref_idx;
+
+ lua_pushcfunction (L, &rspamd_lua_traceback);
+ err_idx = lua_gettop (L);
+
+ /* Load file */
+ if (luaL_loadbuffer (L, str, slen, "lua_embedded_str") != 0) {
+ g_set_error (err,
+ lua_error_quark(),
+ EINVAL,
+ "cannot load lua script: %s",
+ lua_tostring (L, -1));
+ lua_settop (L, err_idx - 1); /* Error function */
+
+ return LUA_NOREF;
+ }
+
+ /* Now call it */
+ if (lua_pcall (L, 0, 1, err_idx) != 0) {
+ g_set_error (err,
+ lua_error_quark(),
+ EINVAL,
+ "cannot init lua script: %s",
+ lua_tostring (L, -1));
+ lua_settop (L, err_idx - 1);
+
+ return LUA_NOREF;
+ }
+
+ if (!lua_isfunction (L, -1)) {
+ g_set_error (err,
+ lua_error_quark(),
+ EINVAL,
+ "cannot init lua script: "
+ "must return function");
+ lua_settop (L, err_idx - 1);
+
+ return LUA_NOREF;
+ }
+
+ ref_idx = luaL_ref (L, LUA_REGISTRYINDEX);
+ lua_settop (L, err_idx - 1);
+
+ return ref_idx;
+}
+
gboolean
rspamd_lua_try_load_redis (lua_State *L, const ucl_object_t *obj,
diff --git a/src/lua/lua_common.h b/src/lua/lua_common.h
index d9e4fcaec..b929ab864 100644
--- a/src/lua/lua_common.h
+++ b/src/lua/lua_common.h
@@ -566,6 +566,15 @@ void rspamd_lua_add_ref_dtor (lua_State *L, rspamd_mempool_t *pool,
gint ref);
/**
+ * Returns a lua reference from a function like string, e.g. `return function(...) end`
+ * @param L
+ * @param str
+ * @return
+ */
+gint rspamd_lua_function_ref_from_str (lua_State *L, const gchar *str, gsize slen,
+ GError **err);
+
+/**
* Tries to load some module using `require` and get some method from it
* @param L
* @param modname