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?
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.
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.