You are not really polluting the global environment, what you see here is a nature of package system, that modules are cached and shared for every call to require
, not depending on environment of calling function. That allows Singleton module to work, because if you will not require
it, but do loadfile
, it will load twice (and be very less singleton than expected).
So, if the real task is to load module only once per sandbox, then you may swap package.loaded
, package.preload
and other loader state variables before entering into a sandbox. More info in Modules
section of Lua 5.1 Reference Manual.
The solution with loadfile
may be just fine, but if you plan to cross-require modules in complex module system inside your sandbox, this will lead to a big problem indeed.