diff --git a/src/common/LuaSupport.cpp b/src/common/LuaSupport.cpp index 50cbd2dd61e..0807e2f7605 100644 --- a/src/common/LuaSupport.cpp +++ b/src/common/LuaSupport.cpp @@ -164,23 +164,21 @@ bool Surge::LuaSupport::setSurgeFunctionEnvironment(lua_State *L) // stack is now f>t>(m). Pop m lua_pop(L, 1); - // clear global table - int stacktest = lua_gettop(L); + // retrieve the "global" table lua_getglobal(L, "global"); - int stacktest2 = lua_gettop(L); - if (lua_type(L, -1) == LUA_TTABLE && lua_type(L, -2) == LUA_TTABLE && - (stacktest2 - stacktest == 1)) - { + // check if the retrieved value is a table + if (lua_istable(L, -1)) { lua_pushnil(L); - while (lua_next(L, -2)) - { + // set table entries to nil + while (lua_next(L, -2)) { lua_pop(L, 1); // pop value lua_pushvalue(L, -1); // duplicate the key lua_pushnil(L); lua_settable(L, -4); // clear the key } - lua_pop(L, 1); } + // pop the retrieved value (either table or nil) from the stack + lua_pop(L, 1); // and now we are back to f>t so we can setfenv it lua_setfenv(L, -2);