A way to load ModuleScripts into a custom environment

Once again I find myself in a situation where having this feature would help me explore into my uncharted territory of allowing community contributions for my creations with ease. Previous post a year back.

As a Roblox developer, there is currently no way to require() a ModuleScript into a custom Lua environment as a form of method to sandbox whatever runs within the ModuleScript.

It would be amazing if we had a method as such:

local module = envrequire(moduleScript, table);

Since we are requiring a ModuleScript into a custom environment, we have the options to either create an arbitrary environment or pass in a reference environment into the method. Once it’s called, calling envrequire on the same module using the same environment would return the the exact same value for subsequent calls like what normal require does on the main environment.

This opens up a possibility where we could have two instances of the same ModuleScript running on different environments.

module.lua

return {Print=function()
    print("Name",Name);
end}

main.lua

local envA = {Name="EnvA"};
local moduleA = envrequire(module, envA);
local moduleB = envrequire(module, {Name="EnvB"});
moduleA.Print(); -- Name EnvA
moduleB.Print(); -- Name EnvB

local moduleC = envrequire(module, envA);
print("Same", moduleA == moduleC) -- Same true

Why?
• Custom community maps would definitely benefit a lot from such feature. It would simplify the process of having many DataValue tags as configuration and have them all within a ModuleScript to configure. It also helps that any malicious code can also get sandboxed.

• Promotes private module, this feature would allow developers to limit what the module can and cannot do. If someone wants to create a complex mathematics library while at the same time monetize it, having this feature would promote the module because devs can just call it into an empty environment and it can do anything malicious.

• LoadStringEnabled can be kept disabled, the current method of running external code in a different environment is done via loadstring but ModuleScripts are more often used to load custom libraries or scripts, if we can loadstring() into a custom environment, why not ModuleScripts?

Please let me know what do you guys think about this feature.

Thanks for reading
~Khronos

10 Likes