So I was experimenting with setfenv() until I came across a problem, so in Roblox when you don’t use global variable for anything other than declaring them they will then be highlighted with a warning and as many of you know that this can be fixed by doing this trick:
NOTE: This works in Lua but not in Roblox because Lua won’t give me a warning for it
local test -- declare test as a local variable then use it later
test = 12 -- test is now not highlighted and Roblox won't warn us
However if you use setfenv() and utilize this trick then it won’t work and the variable that you declared will be equal to nil as if it’s non-existent like so:
local fconfig = {}
function anf (v)
local test -- setfenv() will break because of this so I can only use test
test = v -- I only want to use this but Roblox keeps warning me and the previous mentioned trick doesn't work here
end
setfenv(anf,fconfig)
anf ("yes")
for i, v in next, (fconfig) do
print(tostring(i).." - "..tostring(v)) -- Prints nothing
end
print(fconfig.test) -- test is equal to nil now as if it's non-existent and that's not supposed to happen
Here’s a closer look of the problem in a video so you can see exactly the problem and what I’m talking about:
It says it’s a global variable. You don’t need it to be global, so you can just add a local onto the beginning. The variable will be accessed faster that way. It won’t break the code, it’s only used in that function.
Not really, just sandboxing code, but another use case would be injecting globals into a script. But that isn’t usually a good idea because it can potentially break some scripts