wplua: implement reference counting of the lua_State

This commit is contained in:
George Kiagiadakis
2022-04-04 17:56:36 +03:00
parent 9c22f6076a
commit 9387ce0d95
4 changed files with 43 additions and 17 deletions

View File

@@ -178,7 +178,7 @@ wp_lua_scripting_plugin_disable (WpPlugin * plugin)
{
WpLuaScriptingPlugin * self = WP_LUA_SCRIPTING_PLUGIN (plugin);
g_clear_pointer (&self->L, wplua_free);
g_clear_pointer (&self->L, wplua_unref);
g_clear_object (&self->export_core);
}

View File

@@ -101,14 +101,39 @@ wplua_new (void)
lua_settable (L, LUA_REGISTRYINDEX);
}
/* refcount */
lua_pushinteger (L, 1);
lua_rawsetp (L, LUA_REGISTRYINDEX, L);
return L;
}
lua_State *
wplua_ref (lua_State *L)
{
lua_Integer refcount;
lua_rawgetp (L, LUA_REGISTRYINDEX, L);
refcount = lua_tointeger (L, -1);
lua_pushinteger (L, refcount + 1);
lua_rawsetp (L, LUA_REGISTRYINDEX, L);
lua_pop (L, 1);
return L;
}
void
wplua_free (lua_State * L)
wplua_unref (lua_State * L)
{
wp_debug ("closing lua_State %p", L);
lua_close (L);
lua_Integer refcount;
lua_rawgetp (L, LUA_REGISTRYINDEX, L);
refcount = lua_tointeger (L, -1);
if (refcount > 1) {
lua_pushinteger (L, refcount - 1);
lua_rawsetp (L, LUA_REGISTRYINDEX, L);
lua_pop (L, 1);
} else {
wp_debug ("closing lua_State %p", L);
lua_close (L);
}
}
void

View File

@@ -49,7 +49,8 @@ typedef enum {
} WpLuaSandboxFlags;
lua_State * wplua_new (void);
void wplua_free (lua_State * L);
lua_State * wplua_ref (lua_State *L);
void wplua_unref (lua_State * L);
void wplua_enable_sandbox (lua_State * L, WpLuaSandboxFlags flags);
int wplua_push_sandbox (lua_State * L);
@@ -94,7 +95,7 @@ gboolean wplua_load_path (lua_State * L, const gchar *path, GError **error);
gboolean wplua_pcall (lua_State * L, int nargs, int nres, GError **error);
G_DEFINE_AUTOPTR_CLEANUP_FUNC(lua_State, wplua_free)
G_DEFINE_AUTOPTR_CLEANUP_FUNC(lua_State, wplua_unref)
G_END_DECLS