Require loads and executes code in the global environment.
For example, lets create a simple sandbox (Lua >= 5.2):
-- example.lua
my_global = 42
local sandbox
do
local _ENV = { require = require, print = print }
function sandbox()
print('<sandbox> my_global =', my_global)
require 'example_module'
end
end
print('<global> my_global =', my_global)
sandbox()
print('<global> my_global =', my_global)
Now, lets create a module that changes my_global:
-- example_module.lua
print('<module> my_global =', my_global)
my_global = nil
The expectation is that inside the sandbox the only functions available are require and print. Code inside the sandbox should not be able to access the global my_global.
Run the example and you will see:
$ lua example.lua
<global> my_global = 42 -- The global environment, Ok.
<sandbox> my_global = nil -- Inside the sandbox, Ok.
<module> my_global = 42 -- Inside the sandbox, but loaded with require. Whoops, we have access to the global environment.
<global> my_global = nil -- The module changed the value and it is reflected in the global environment.
The module has broken out of the sandbox.