Don’t use getfenv/setfenv in new work.
This resource is outdated and based on old knowledge. This resource was written purely because I found it cool that a certain asset was able to use custom globals so I wanted to figure out how I could do that myself and share my knowledge.
Following the “official release” of Luau, there are only very niche cases where setting function environments is necessary. Most new work should not need to use it and any use cases for it should be resolved with ModuleScripts. Environments can become impure by setting or even just getting them and various optimisations Luau provides will be nullified.
It’s also important to note that there’s an RFC for deprecating getfenv/setfenv in Luau that has been pulled to the repository, so it’s likely there will be official recommendation against using them.
See: Importing global access chains / Deprecate getfenv/setfenv
Please read before proceeding.
This is not a reliable resource and should not be used anymore I created this in 2018 with a lack of strong knowledge about function environments and made this on the basis of “I think it’s cool an asset is able to use custom globals”, that’s it. This resource is merely a primer for using getfenv/setfenv but it does not explore the concept of function environments deeply. Additionally, please see the above section exploring use of these in code.
You will most likely not have any reason to use get/setfenv. I know I don’t. I made a model anyway and I open-sourced it some time back. I’m bringing it to the DevForum because I want to have a post in Community Resources and I feel like sharing this. Also in that respect, if you ever find yourself needing to use either get/setfenv, you have this which you can read, salvage or do whatever you want. You could even make a framework or system set up in this fashion.
Here you go: https://www.roblox.com/library/1292841947/API-Example
(AS OF 2022 MAY 30, I have taken this model offsale. I do not want to encourage bad practice and I have no intentions to update either this resource or the thread.)
No, that isn’t really API. It’s a script I created after referencing what SyncAdmin did to have their commands work. In their plugins (commands, both ones that come with the model and ones that you can write), you can use certain methods off of “SyncAPI”. It gives a blue underline because it’s like an unknown global variable in-script, but methods actually work because SyncAPI is defined via setfenv in a private-source module.
SyncAPI.SomeFunctionFromTheAPI
^ Without setfenv, that normally wouldn’t work.
Leave feedback, comments or whatever below. Feel free to message me if you notice something off about my code as well - I am still learning and far from having a good arsenal of scripting knowledge and power.