From 36d4c9298f4be2d1c1fb803dc16948e3c11a3a49 Mon Sep 17 00:00:00 2001 From: Matthias Schiffer Date: Sun, 28 Sep 2014 20:41:37 +0200 Subject: Clean the Lua context after a script has run --- src/control/ScriptContext.hpp | 44 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 9 deletions(-) (limited to 'src/control') diff --git a/src/control/ScriptContext.hpp b/src/control/ScriptContext.hpp index 34dc8fc..23f0fab 100644 --- a/src/control/ScriptContext.hpp +++ b/src/control/ScriptContext.hpp @@ -44,13 +44,7 @@ class ScriptContext { private: lua_State *L; -public: - ScriptContext(const ScriptContext &other) = delete; - ScriptContext(ScriptContext &&other) = delete; - ScriptContext & operator=(const ScriptContext &other) = delete; - ScriptContext & operator=(ScriptContext &&other) = delete; - - ScriptContext() { + void setupEnv() { const std::pair libs[] = { {"_G", luaopen_base}, {"bit32", luaopen_bit32}, @@ -59,8 +53,6 @@ public: {"table", luaopen_table}, }; - L = luaL_newstate(); - for (auto &lib : libs) { luaL_requiref(L, lib.first, lib.second, 1); lua_pop(L, 1); @@ -70,6 +62,35 @@ public: lua_pushnil(L); lua_setglobal(L, f); } + } + + void cleanupEnv() { + lua_pushglobaltable(L); + + lua_pushnil(L); + lua_setmetatable(L, -2); + + lua_pushnil(L); + while (lua_next(L, -2) != 0) { + lua_pop(L, 1); + + lua_pushvalue(L, -1); + lua_pushnil(L); + + lua_rawset(L, -4); + } + + lua_pop(L, 1); + } + +public: + ScriptContext(const ScriptContext &other) = delete; + ScriptContext(ScriptContext &&other) = delete; + ScriptContext & operator=(const ScriptContext &other) = delete; + ScriptContext & operator=(ScriptContext &&other) = delete; + + ScriptContext() { + L = luaL_newstate(); lua_newtable(L); lua_rawsetp(L, LUA_REGISTRYINDEX, this); @@ -90,10 +111,15 @@ public: } void run(const std::string &name) { + setupEnv(); + lua_rawgetp(L, LUA_REGISTRYINDEX, this); lua_getfield(L, -1, name.c_str()); lua_remove(L, -2); + lua_call(L, 0, 0); + + cleanupEnv(); } }; -- cgit v1.2.3