Skip to content

Commit

Permalink
Fix nested calls to AI action handlers clobbering the ai table
Browse files Browse the repository at this point in the history
(For example, if a Lua candidate action queries a Lua aspect.)
  • Loading branch information
CelticMinstrel authored and mattsc committed Mar 22, 2016
1 parent 3939d2a commit aa791ce
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/ai/lua/core.cpp
Expand Up @@ -1087,6 +1087,8 @@ lua_ai_action_handler* lua_ai_action_handler::create(lua_State *L, char const *c
}


int lua_ai_load::refcount = 0;

lua_ai_load::lua_ai_load(lua_ai_context& ctx, bool read_only) : L(ctx.L)
{
lua_pushlightuserdata(L, static_cast<void *>(const_cast<char *>(&aisKey))); // [-1: key]
Expand All @@ -1100,13 +1102,18 @@ lua_ai_load::lua_ai_load(lua_ai_context& ctx, bool read_only) : L(ctx.L)
lua_pushboolean(L, read_only); // [-1: value -2: key -3: AI functions -4: AI state]
lua_rawset(L, -3); // [-1: AI functions -2: AI state]
lua_setglobal(L, "ai"); // [-1: AI state]

refcount++;
}

lua_ai_load::~lua_ai_load()
{
// Remove the AI functions from the global scope
lua_pushnil(L);
lua_setglobal(L, "ai");
refcount--;
if (refcount == 0) {
// Remove the AI functions from the global scope
lua_pushnil(L);
lua_setglobal(L, "ai");
}
}

lua_ai_context::~lua_ai_context()
Expand Down
1 change: 1 addition & 0 deletions src/ai/lua/core.hpp
Expand Up @@ -58,6 +58,7 @@ class lua_ai_context
class lua_ai_load
{
lua_State* L;
static int refcount;
public:
lua_ai_load(lua_ai_context& ctx, bool read_only);
~lua_ai_load();
Expand Down

0 comments on commit aa791ce

Please sign in to comment.