Browse Source

Added a _THIS field to the environment of private scripts, which operates similar to _G for global scripts. Private scripts can use the _THIS field to expose their interface to other scripts by doing something like: _G.myScript = _THIS

sgrenier 11 years ago
parent
commit
062b8563e4
1 changed files with 7 additions and 1 deletions
  1. 7 1
      gameplay/src/ScriptController.cpp

+ 7 - 1
gameplay/src/ScriptController.cpp

@@ -243,7 +243,7 @@ bool ScriptController::loadScript(Script* script)
 
 
             // Create a metatable that forwards missed lookups to global table _G
             // Create a metatable that forwards missed lookups to global table _G
             lua_newtable(_lua); // metatable [chunk, env, meta]
             lua_newtable(_lua); // metatable [chunk, env, meta]
-            lua_getglobal(_lua, "_G"); // pushes _G, which will be the __index metatable entry [chunk, env, meta, _G]
+            lua_pushglobaltable(_lua); // pushes _G, which will be the __index metatable entry [chunk, env, meta, _G]
 
 
             // Set the __index property of the metatable to _G
             // Set the __index property of the metatable to _G
             lua_setfield(_lua, -2, "__index"); // metatable on top [chunk, env, meta]
             lua_setfield(_lua, -2, "__index"); // metatable on top [chunk, env, meta]
@@ -251,6 +251,12 @@ bool ScriptController::loadScript(Script* script)
             // Set the metatable for our new environment table
             // Set the metatable for our new environment table
             lua_setmetatable(_lua, -2); // [chunk, env]
             lua_setmetatable(_lua, -2); // [chunk, env]
 
 
+            // Store a pointer to the ENV table in the table itself, so it can refer to itself.
+            // This is similar to how the _G field works for accessing the global table, and
+            // how _G._G is valid.
+            lua_pushvalue(_lua, -1); // [chunk, env, env]
+            lua_setfield(_lua, -2, "_THIS"); // [chunk, env]
+
             // Set the first upvalue (_ENV) for our chunk to the new environment table
             // Set the first upvalue (_ENV) for our chunk to the new environment table
             if (lua_setupvalue(_lua, -2, 1) == NULL) // [chunk]
             if (lua_setupvalue(_lua, -2, 1) == NULL) // [chunk]
             {
             {