How to use getfenv() function

Hello Roblox Developers! Thank you for reading my topic and today you are learning how to use getfenv(). I hope you enjoy this and please consider me more post ideas for teaching more things.

First To Do

  1. Make a ‘ServerScript’ in ServerScriptService
  2. Have Fun!

Step 1.

Make a function

function myFunc()
    print(message) --// No need for parameter
end

Step 2.

Making a getfenv()

function myFunc()
    print(message)
end

local env = getfenv(myFunc) --// Here is getting everything in the function

Step 3.

Finishing the fenv

function myFunc()
    print(message) --// It will show an error here ignore that it is just a natural reaction this will not affect the code
end

local env = getfenv(myFunc)
env.message = "Hello World!"

myFunc()

Extra Info

It does not even need to be message it can be this

function myFunc()
    print(myMessage)
end

local env = getfenv(myFunc)
env.myMessage = "Hello World!"

myFunc()

Ending!

There you go! You just created a getfenv() function. Please ignore the error that looks like this image It will still print this image

Done

5 Likes

You didn’t “create” a getfenv function, could you explain where this would be useful ? The use of setfenv and getfenv is actively discouraged, as their use could disable some of Luau’s optimizations.

5 Likes

But why would you use genfenv when you can just do:

function myFunc(msg)
   print(msg)
end

myFunc("Hello")

I just don’t understand the point of using getfenv and didn’t really learn anything at all. Why not use parameters instead?

1 Like

The example given by the OP isn’t the best. getfevn and setfevn is mostly useful for cross script variable injection. It’s still useful to learn despite being discouraged to use imo.

Although I do agree that the quality of this it’s not even close to being useful, the article from DevHub is a lot better.

2 Likes

Like this

local function myFunc()
    print(msg)
end

local env = getfenv(myFunc)
env.msg = “hi”

myFunc()

It will show orange underline ignore that

This is a really really really bad tutorial explaining getfenv(). You failed to explain what getfenv() and setfenv() actually do, what a function environment is, use cases, etc. Your own tutorial makes it seem like you really don’t know what you’re even writing about.

And sandboxing, mostly inside of SB games.