I’m trying to learn setfenv but when I attemptted to script something with it did this
> Workspace.Script:2: attempt to call a nil value
Script:
setfenv(1,{["Test"] = 1})
print(getfenv(2).Test)
I’m trying to learn setfenv but when I attemptted to script something with it did this
> Workspace.Script:2: attempt to call a nil value
Script:
setfenv(1,{["Test"] = 1})
print(getfenv(2).Test)
You are setting the current envionment, 1
, to only have the variable Test
. getfenv
with argument 2
gets the parent environment. So getfenv
does not exist in the new environment.
changed it to
setfenv(1,{["Test"] = 1})
print(getfenv(1).Test)
still does the same error
Because print
and getfenv
does not exist in the given environment.
setfenv(1, { Test = 1, getfenv = getfenv })
print(getfenv(1).Test, Test)
edit: nvm doesnt work lol
What do I do??? (30 30 30 30 30 characters)
Nvm I fixed it I had to add “Print”
Yeah I figured that was it. I was gonna also say “add setfenv
to the environment as well” but that seemed unnecessary after testing.
Although this is relatively off-topic, figure I say it anyway: unless you’re intending to use Lua outside of Roblox, you should stop learning about get/setfenv. Learning about script environments is fine but you should never actually use these two functions for two reasons:
This injects globals into the environment. You should always be aiming to use locals as those variables become accessible only to the current scope. It’s good practice to use locals over globals.
Changing the script environment disables the optimisations that Luau provides, which is not favourable. Don’t sacrifice performance over making your code, which possibly no one will actually ever read, look pretty.
This is mainly just for testing reasons, I prefer modules anyway.
Ah, gotcha, thanks for letting me know. Modules definitely have a lot more power and I do prefer them as well. You’ll never actually find yourself using custom environments in Roblox, haha.
Anyway, sorry for the off-topic remark, just thought I would leave that around. Have you resolved this problem yet or are you still looking for responses? I see you haven’t marked anything.
I have an old resource on this if you’re interested. It’s not refined at all, but there is some discussion that might help you around. Here:
Thanks, but either way I didn’t know that setfenv()
was bad practice.