Commits

Bart van Strien committed 2593461

Move the references from _G to the registry

Comments (0)

Files changed (2)

src/common/Reference.cpp

 
 namespace love
 {
+	const char REFERENCE_TABLE_NAME[] = "love-references";
+
 	Reference::Reference()
 		: L(0), idx(LUA_REFNIL)
 	{
 	{
 		unref(); // Just to be safe.
 		this->L = L;
-		idx = luaL_ref(L, LUA_GLOBALSINDEX);
+		luax_insist(L, LUA_REGISTRYINDEX, REFERENCE_TABLE_NAME);
+		lua_insert(L, -2); // Move reference table behind value.
+		idx = luaL_ref(L, -2);
+		lua_pop(L, 1);
 	}
 
 	void Reference::unref()
 	{
 		if (idx != LUA_REFNIL)
 		{
-			luaL_unref(L, LUA_GLOBALSINDEX, idx);
+			luax_insist(L, LUA_REGISTRYINDEX, REFERENCE_TABLE_NAME);
+			luaL_unref(L, -1, idx);
+			lua_pop(L, 1);
 			idx = LUA_REFNIL;
 		}
 	}
 	void Reference::push()
 	{
 		if (idx != LUA_REFNIL)
-			lua_rawgeti(L, LUA_GLOBALSINDEX, idx);
+		{
+			luax_insist(L, LUA_REGISTRYINDEX, REFERENCE_TABLE_NAME);
+			lua_rawgeti(L, -1, idx);
+			lua_remove(L, -2);
+		}
 		else
 			lua_pushnil(L);
 	}

src/common/runtime.cpp

 
 	int luax_insist(lua_State * L, int idx, const char * k)
 	{
+		// Convert to absolute index if necessary.
+		if (idx < 0 && idx > LUA_REGISTRYINDEX)
+			idx = lua_gettop(L) + ++idx;
+
 		lua_getfield(L, idx, k);
 
 		// Create if necessary.
 			lua_pop(L, 1); // Pop the non-table.
 			lua_newtable(L);
 			lua_pushvalue(L, -1); // Duplicate the table to leave on top.
-			lua_setfield(L, -3, k); // k[idx] = table
+			lua_setfield(L, idx, k); // lua_stack[idx][k] = lua_stack[-1] (table)
 		}
 
 		return 1;