How do I fix this variable being highlighted as a warning from Roblox without breaking the code?

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:

1 Like

That is Roblox just suggesting you to use a local variable. Orange/yellow lints are just warnings; they don’t mean your code won’t work.

Red lints are pointing out errors in the syntax and confirm that your code won’t work.

You generally shouldn’t use setfenv nor getfenv; using them disables certain Luau optimizations.

It’s still a local variable btw. You are just redefining it.

1 Like

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.

Are there alternatives for setfenv and getfenv since you don’t recommend me to use them with Luau?

Not that i know of, unfortunately. Are you just wanting to use this for sandboxing or what?

1 Like

Yes, I wanted to use them for sandboxing and also experimenting with how they generally work but thank you for your help.

One more last question thought, are there cases where I will need to utilize setfenv() and getfenv() in Roblox or no?

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

1 Like