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

What does the 1 mean in getfenv(1)?

Asked by
funyun 958 Moderation Voter
8 years ago

I know the environment is just all the variables in the script. What I don't know is what the 1 means. What if I put 0 or 2 there? What if I put a function there?

1 answer

Log in to vote
6
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

getfenv(f) gives you a table representing the global variables a given function f has.

f can either be a number or a function.

If it's a number, then you look that number of levels "up" in callers to figure out which function it's referring to. 1 is the default, and means the function calling getfenv. 0 is special and means the global environment (the "normal" one, all the way at the top).

function a()
    b()
end

function b()
    c()
end

function c()
    d()
end

function d()
    getfenv(1) -- gets env of d
    getfenv(2) -- gets env of c
    getfenv(3) -- gets env of b
    getfenv(4) -- gets env of a
    getfenv(5) -- gets global environment
    getfenv(0) -- gets global environment.
end

a()

If f is a function, then you just get the environment of that function.

Normally, the "environment" of every function is just the table of global variables. This will only be changed with setfenv. The environment is what is looked to when a variable is referred to and that variable is not in scope as a local variable.


It is not wise to do too much to the function environment, because it can make debugging or understanding code almost impossible.

getfenv and setfenv should be used sparingly.

The only truly acceptable use I've heard of is erroring on undefined variables, though ROBLOX's Script Analysis will catch this anyways:

local old = getfenv()
local new = {}
setmetatable(new, {__index = function(_, name) return old[name] or error("`" .. name .. "` is not defined", 2) end})
setfenv(0, new)
Ad

Answer this question