Skip to content

Commit

Permalink
Optimize stacktrace functionality (#477)
Browse files Browse the repository at this point in the history
We now push the function to stack only once and never shift all function call arguments around.
  • Loading branch information
Rochet2 authored Apr 8, 2024
1 parent 3d1ead7 commit 24cae10
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 12 deletions.
21 changes: 9 additions & 12 deletions LuaEngine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ void Eluna::CloseLua()
if (L)
lua_close(L);
L = NULL;
stacktraceFunctionStackIndex = 0;

instanceDataRefs.clear();
continentDataRefs.clear();
Expand Down Expand Up @@ -163,6 +164,10 @@ void Eluna::OpenLua()
lua_pushcfunction(L, &PrecompiledLoader);
lua_rawseti(L, -2, newLoaderIndex);
lua_pop(L, 2); // pop loaders/searchers table, pop package table

// Leave StackTrace function on stack and save reference to it
lua_pushcfunction(L, &StackTrace);
stacktraceFunctionStackIndex = lua_gettop(L);
}

void Eluna::CreateBindStores()
Expand Down Expand Up @@ -355,24 +360,16 @@ bool Eluna::ExecuteCall(int params, int res)
}

bool usetrace = sElunaConfig->GetConfig(CONFIG_ELUNA_TRACEBACK);
if (usetrace)
if (usetrace && !lua_iscfunction(L, stacktraceFunctionStackIndex))
{
lua_pushcfunction(L, &StackTrace);
// Stack: function, [parameters], traceback
lua_insert(L, base);
// Stack: traceback, function, [parameters]
ELUNA_LOG_ERROR("[Eluna]: Cannot execute call: registered value is %s, not a c-function.", luaL_tolstring(L, stacktraceFunctionStackIndex, NULL));
ASSERT(false); // stack probably corrupt
}

// Objects are invalidated when event_level hits 0
++event_level;
int result = lua_pcall(L, params, res, usetrace ? base : 0);
int result = lua_pcall(L, params, res, usetrace ? stacktraceFunctionStackIndex : 0);
--event_level;

if (usetrace)
{
// Stack: traceback, [results or errmsg]
lua_remove(L, base);
}
// Stack: [results or errmsg]

// lua_pcall returns 0 on success.
Expand Down
4 changes: 4 additions & 0 deletions LuaEngine.h
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,10 @@ class ELUNA_GAME_API Eluna
// Whether or not Eluna is in compatibility mode. Used in some method wrappers.
bool compatibilityMode;

// Index of the Eluna::StackTrace function pushed to the lua state stack when lua is opened
// We store the function to stack on lua open because it cannot be a pseudo-index (must be on stack) and we want access it on every call
int stacktraceFunctionStackIndex = 0;

// Map from instance ID -> Lua table ref
std::unordered_map<uint32, int> instanceDataRefs;
// Map from map ID -> Lua table ref
Expand Down

0 comments on commit 24cae10

Please sign in to comment.