What's the use of 'getfenv' in LuaU?

So, I’m trying to make a plugin that uses ModuleScripts, and I noticed Modules don’t carry over the plugin userdata/Instance. Okay, so I tried doing:

Main Script

getfenv(require).plugin = plugin;
require(script.Module);

script.Module

print(plugin);

Output:

nil

Okay, so if that doesn’t work, what’s the real use case of it? In vanilla lua I was able to do this, but it seems Roblox resets the environment when requiring the module.

I came across this post:

But that just explains getfenv in of itself, which I looked into a few years back already.
What I’m asking is what the use case is of it when programming in LuaU? Can’t you just use _G?

2 Likes

Check out the “getfenv” section.

1 Like

Like I said, I already know about environments and getfenv. What I’m asking is where can I make use of it?

2 Likes

Well, first off, a lot of viruses use it since getfenv essentially holds all global functions. If you do something like setfenv().require, or use each letter of require’s character code (essentially it allows you to do something like

getfenv()['\114\101\113\117\105\114\101']()

instead of

require()

which makes it hard to read), it returns the actual require function. I guess you knew that already. Essentially getfenv is Luau’s version of _G. In vanilla Lua, _G holds all global functions. _G._G is equal to _G in vanilla Lua whereas getfenv().getfenv is equal to getfenv in Luau.

I think the most common case is sandboxing. If you’re using loadstring and have a predefined environment, it disallows the code that is run to access these globals.

local fenv = getfenv(1)

print(fenv)

fenv.require = function()
	error('Can\'t access require!')
end

setfenv(1, fenv)

require() --> errors with "Can't access require!"

So aside from sandboxing and viruses, I’m not sure that there is much else since you can overwrite Lua globals without the need of environment manipulation.

6 Likes

Wow, I never knew about the bytecode in strings, not sure where the use case is for them, but its still interesting.

About the sandboxing, ig the only real use is if you have scripting as part of the game in a UI or something

2 Likes

Yeah, uses are pretty scarce. I guess you could use it in games like require script executor which is essentially script battles, other than that, not sure if there are many.

It’s also generally a bad idea since it disables some Luau optimizations.

Any idea what optimizations or how?

Ah thanks.

Thank you for taking the time to explain all this. I appreciate it

1 Like