title: Changing the _ENV of a lua_thread (using C API)
body: <p>This is for a multiplayer game where NPC scripts will be loaded and cached as function chunks on a single lua_State, and then each time a player interacts with an NPC, a new lua_thread is created, a cached function is fetched from a global lua_table and pushed onto the thread's stack, and then the thread is resumed (the npc script yields several times before finishing). </p>
  
  <p>I am trying to change the environment of the lua thread using the C API, so that the function that has been loaded/run will not be able to change global variables / have them changed by other functions running on a different thread.</p>
  
  <p>I achieved desired results by changing the functions environment, by adding this code to the start of my script. However I would like to do this using the C API side, so that I don't have to paste this code into every single script.</p>
  
  <pre><code>local newgt = {}
  setmetatable(newgt, {__index = _G })
  local _ENV = newgt
  </code></pre>
  
  <p>Example code + desired / current output</p>
  
  <p>npcA.lua</p>
  
  <pre><code>x = 10
  print(x)
  y = 60
  </code></pre>
  
  <p>npcB.lua</p>
  
  <pre><code>print(x)
  y = 25
  player:someYieldingFunction()
  print(y)
  </code></pre>
  
  <p>I expect that npcA print</p>
  
  <pre><code>10
  </code></pre>
  
  <p>and that npcB print</p>
  
  <pre><code>nil
  25
  </code></pre>
  
  <p>The output currently is (this is not what I want)</p>
  
  <p>if npcA runs first npcB would print</p>
  
  <pre><code>10
  25
  </code></pre>
  
  <p>if npcB runs first and then yields, then npcA runs, and then npcB resumes.
  npcB would print</p>
  
  <pre><code>10
  60
  </code></pre>
  
  <p>which is problematic</p>