If one wants to execute a piece of lua code in a "protected" environment (so that functions, globals, etc... are not messed up afterwards), it seems the way to go is load(), with an environment param:
x = 0
env = {}
setmetatable(env, {__index = _G})
assert(load('x = 999', 'foo.lua', 't', env))()
print(x) -- x is still 0, env.x is 999
however, if the code to run calls require, then it escapes the protected environment:
x = 0
env = {}
setmetatable(env, {__index = _G})
assert(load('require "ext"', 'foo.lua', 't', env))() -- ext.lua contains `x = 999`
print(x) -- x is 999! (so is env.x...)
is this intended, and how to properly protect in the second case?