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

Is getfenv()'s argument useless?

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.

2 comments

0

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

1 answer

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.

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