Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 4 years ago

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
pls dont forget about me :(( incapaz 195 — 4y

1 answer

Log in to vote
2
Answered by
incapaz 195
4 years ago
Edited 4 years ago

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.

0
thanks maumaumaumaumaumua 628 — 4y
Ad

Answer this question