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).
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.
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.
local newgt = {}
setmetatable(newgt, {__index = _G })
local _ENV = newgt
Example code + desired / current output
npcA.lua
x = 10
print(x)
y = 60
npcB.lua
print(x)
y = 25
player:someYieldingFunction()
print(y)
I expect that npcA print
10
and that npcB print
nil
25
The output currently is (this is not what I want)
if npcA runs first npcB would print
10
25
if npcB runs first and then yields, then npcA runs, and then npcB resumes. npcB would print
10
60
which is problematic