Working with script environments!

Hey, I’m sleepcodes! I just wanted to share a cool little trick I learned with you Open-Source module developers!

What does this do?
Basically, this code allows you to export functions from your module into the scripts environment for easier usage.

ModuleScript Code
return function(func)
	assert(func ~= nil and type(func) == "function" and func == require,"invalid argument #1 (must be function \"require\")")
	local externalSenv = getfenv(func)
	local internalSenv = getfenv(require)
	externalSenv["load"] = function()
		local script = externalSenv["script"]
		print("Hello!")
	end
end
Script Code
require(game.ServerStorage.ModuleScript)(require)

load()
Output
Hello!  -  Server - ModuleScript:7

Warning! The code functions exported still execute in the ModuleScript, I guess that’s how roblox works :confused: Also, when using the function you must send the “require” function as a parameter.

Why would you use this?

I honestly don’t know! I just thought this would be a cool thing to try out and see how it could shorten your code!

3 Likes

Can’t you use getfenv(2) instead of passing a function?
e.g:

-- ModuleScript
return function()
    local ext = getfenv(2)
    ext.load = function()
        print("Hello!")
    end
end
-- Script
require(game.ServerStorage.ModuleScript)()
load()
1 Like