Problems with getfenv()

Hello there.

I’m beginning to learn about getfenv() and I’m a bit stuck. I’m attempting to make a system that reads a variable from a function it calls, without running the function and getting a return.

for instance:

function test1()
    local _info = "This is a message!"
end

function test2()
    local _info = "This is a message also!"
end

print(getfenv(test)._info)

I wan’t to be able to print _info from within the function.

I’ve tried using:

function test1()
   
end

function test2()

end

getfenv(test1)._info = "This is a message!"
getfenv(test2)._info = "This is a message also!"

print(getfenv(test1)._info) -- prints "This is a message!"

But I have many functions within the same “environment” that need to have specific messages within them. It seems like _info is being set as a global here, so the last _info set would be the one it prints. Is there a way to isolate getfenv() and exclude everything outside of it?

Hopefully, this makes sense. I’m running off of little sleep lol.

Thanks in advance.

This is what setfenv is for; sandboxing.

setfenv(test1, { _info = "This is a message!" })
setfenv(test2, { _info = "This is a message also!" })
print(getfenv(test1)._info)
print(getfenv(test2)._info)
1 Like

Only issue with using setfenv() is that it replaces my existing function environment. It seems to make the function not work because it’s getting set afterward. Is there a way to add to the environment?

Figured it out!

local env = getfenv(module.quarentine.examine)
env["_info"] = "mystr"

setfenv(module.quarentine.examine, env)

Thanks again!

1 Like

Friendly reminder that getfenv().x only works after you’ve called that function, and that variable has been declared. This only works with global variables. Here’s example code showing this:

function f()
    x = 10
end
print(getfenv(Hello).x) --> nil
f()
print(getfenv(Hello).x) --> 10
1 Like

Okay, I see. It looks like I will need to rework my system to accommodate this. Really good information to know.