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?
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(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.