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

Getting the environment of a function within a function?

So lets say I have a modulescript and I want to iterate through every variable I declared within module.new() from module.new()

what argument to getfenv() would you use?

For example, this is a modulescript in workspace

local module = {}
function module.new()
	local asdf = "ASDF"
	local num = 1
	local char = 'a'
	for _, v in pairs(getfenv()) do
		print(v);
	end
end
module.__index = module
return module

and this is another script in workspace

local test = require(script.Parent.ModuleScript)

test.new()

Yet when it runs, it only prints the name of the ModuleScript

1 answer

✓ Accepted answer

Use getfenv(2) to get the function environment from the stack level that the function came from. Alternatively, pcall your way up to get to the top stack level if you want the invoking script's env

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