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

Is getfenv()'s argument useless?

Asked by
LuaQuest 450 Moderation Voter
8 years ago

So, i know that getfenv() returns the global function environment. However, I've been messing around with it a bit, and it just seems to me that the argument in getfenv() is useless? Here are some examples I've tried:

a = 1
b = 2

local function v()
    c = 3
end

for i,v in pairs (getfenv(v)) do
    print(i,v) 
end

-- Output -- >> a 1, b 2, c 3, script Script
-- But why? I thought i was getting the function environment for "v" only?

Here's another:

a = 1

local function x()
    b = 2
    local function v()
        for i,v in pairs (getfenv(2)) do -- Now using 2 to represent the stack level (which should be in function "x"?)
            print(i,v)
        end
    end
    v()
end

x()

-- Output -- >a 1, b 2, script Script

Real question

So i guess my question is, why does getfenv(function/stack level) constantly return the global script environment when i specifically gave it a function environment to return (oppose to the global one)? Thank you for your time, and hope you can help.

0
From that Q: "Normally, the 'environment' of every function is just the table of global variables. This will only be changed with setfenv." BlueTaslem 18071 — 8y

1 answer

Log in to vote
0
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
8 years ago

The default environment of any function is the global environment. A function environment will only be changed by setfenv. Function environments are used for sandboxing and tracking variables.

See this answer for a more detailed explanation of getfenv.

Ad

Answer this question