How to use getfenv and setfenv

Hey developers, I know there is a topic on this. I read this post “What does ``getfenv()`` do? - #4 by colbert2677”. I was only able to only understand that it gets the environment of the script or something. Any help thanks!

2 Likes

I suggest reading this while you are at it, as @AsynchronousMatrix does a lot better job than I can do.

2 Likes

My post is not intended to explain what get/setfenv do, it’s meant to correct a misconception about a specific resource and how it handles loading code into other ModuleScripts. I also plugged a small example about get/setfenv’s use but never explained what they are or how they’re used. I’m not even sure why that’s marked as the solution because it doesn’t answer the original question.

I encourage you to read the post made below by kiriot22 as that is an actual, accurate and simplified version of what get/setfenv do; not just that, but the post also explains what exactly its modifying. Post #6 on the thread. This is the real solution to that thread.

This all being said, you should never have a reason to use get/setfenv in 2021. Not only does it purportedly disable optimisations by Luau but there’s generally no point in modifying the script’s environment when you can use ModuleScripts instead. A hard exception might be if you need to sandbox code but at that point you should just be manually reviewing said code and not allowing arbitrary running of it in your games.

4 Likes

does getfenv or setfenv allow you to access variables inside other scripts?

No, environment changes only apply to the function you call it on.

If you want to share variables across scripts, consider ModuleScripts.

3 Likes

For help on how to use it use this. And for a little bit more info here.

Here’s a link to the whole thread but the last few posts are just people saying good job.

Here’s a little bit more info on getfenv() and setfenv() that I found on the internet.

getfenv(f)

Returns the environment of the given function. If no function is given, getfenv returns the environment of the running function.

setfenv(f, table)

Sets the environment to be used by the given function. f can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function calling setfenv. setfenv returns the given function.

As a special case, when f is 0 setfenv changes the environment of the running thread. In this case, setfenv returns no values.

If you need to know more, check out the link I provided.

Thanks for reading! I hope this helped!

Here is the link to the original post: https://devforum.roblox.com/t/how-to-use-getfenv-and-setfenv/402621?u=colbert2677