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

Getting the environment of a function within a function?

Asked by 9 years ago

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

Log in to vote
0
Answered by 9 years ago

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

Ad

Answer this question