Clean the Lua context after a script has run
This commit is contained in:
parent
a5f288ca3f
commit
36d4c9298f
1 changed files with 35 additions and 9 deletions
|
@ -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();
|
||||
}
|
||||
};
|
||||
|
||||
|
|
Reference in a new issue