Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do getfenv and setfenv functions work? And what is their usages?

What am i trying to do

Know the usage of getfenv and setfenv and know if it works for a sandbox

My problem

Don't exactly know how to use them

My attempts to resolve the problem

When i was testing getfenv i noticed that it is a table so i used this

table.foreach(getfenv(),print)

Nothing was printed out, and still didnt know how to figure out its usage

What is my question

How does getfenv and setfenv work? Is it good for making script sandboxes? What are their usage?

1 comment

1

pls dont forget about me :((

1 answer

✓ Accepted answer

Just a side note: table.foreach is deprecated, use a generic for loop instead.

setfenv

setfenv(f, env) sets a function's environment. When it receives a function as the first argument, it will set f's environment to env . The env table is a dictionary of what will be the variables for the functions environment.

Here is an example:

local function fn()
	print("Fn")
end

setfenv(fn, { })
fn()

You will get an exception like attempt to call a nil value, because the environment is empty.

Now let's add print variable in the environment of fn.

setfenv(fn, { print = print })
fn() --> Fn

When called with 1, it will set the environment of the current environment.

setfenv(1, { })
print("XD")

The same attempt to call a nil value exception.

You could use 2, which is another environment, however I am unsure of what it exactly is. I think there are numbers you could use too.

getfenv

getfenv(fn) is practically the opposite. It gets an environment. Knowing how setfenv works now, I think I don't need to explain further. The numbers thing is still the same.

1 comment

0

thanks

This discussion is preserved as it was. New answers, comments, and votes are closed.