summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorMatthias Schiffer <mschiffer@universe-factory.net>2014-09-28 20:41:37 +0200
committerMatthias Schiffer <mschiffer@universe-factory.net>2014-09-28 20:41:37 +0200
commit36d4c9298f4be2d1c1fb803dc16948e3c11a3a49 (patch)
treef4760c865775299006dcb4bfcd5a0cda1897849f /src
parenta5f288ca3f4621ad60ed270a2e95ef8acc6c90d2 (diff)
downloadrpgedit-36d4c9298f4be2d1c1fb803dc16948e3c11a3a49.tar
rpgedit-36d4c9298f4be2d1c1fb803dc16948e3c11a3a49.zip
Clean the Lua context after a script has run
Diffstat (limited to 'src')
-rw-r--r--src/control/ScriptContext.hpp44
1 files changed, 35 insertions, 9 deletions
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<const char *, lua_CFunction> 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();
}
};