How would I use setfenv on a function?

I was wondering how setfenv works with a function. However, setfenv didn’t show an example of what happens to do it with a function. As I was testing this, the function prints out the original variable.

If you’re wondering, I know this works with getfenv differently.

msg = 'none'
function start()
   print(msg)
end

setfenv(start, getfenv(start, {msg = 'hello'))() -- none

How would setfenv work with a function?

getfenv gets a function’s environment. You just need to pass the table

setfenv(start, { msg = "hello" })

If you’re asking for real-world use cases, one would be sandboxing. Though do note that using setfenv and getfenv disable some of Luau’s optimizations, so I recommend against it now.

4 Likes

I’d like to know a bit more about why and what optimizations setfenv and getfenv disable, have had some issues finding resources on this case.

2 Likes