diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/control/ScriptContext.hpp | 44 |
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(); } }; |