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