Local variable (but in overlapping loop)

i have a loop to set up some variables

  for v=1,5 do
   local getfenv()[v]= "alpha"
  end

that loop is inside a loop

for i,f in pairs (table) do--big loop
  for v=1,5 do -- small loop
   local getfenv()["c"..v]= "alpha" 
  end
end

if I do this

for i,f in pairs (table) do--big loop
  for v=1,5 do -- small loop
   local getfenv()["c"..v]= "alpha" 
  end
print (c1) --print1
end
print (c1)-- print2

I get

nil -- from print 1
nil -- from print 2

if I do this

for i,f in pairs (table) do--big loop
  for v=1,5 do -- small loop
    getfenv()["c"..v]= "alpha" 
  end
print (c1) --print1
end
print (c1)-- print2

I get

alpha-- from print 1
alpha -- from print 2

what I want as output is

alpha-- from print 1
nil -- from print 2
1 Like

First of all, I would not recommend creating global variables using getfenv() anyways because it is not very readable. If you want to achieve this behavior, just use a table. For example:

local yourValues = {} -- Empty table, instead of getfenv()'s table
for i,f in pairs (table) do--big loop
  for v=1,5 do -- small loop
      yourValues["c"..v] = "alpha"
  end
print (yourValues.c1) --print1
end
print (yourValues.c2)-- print2

Regardless, I think what you are doing wrong is the local portion of the script. getfenv() is a function, not a variable, which returns the table of global namespaces. When you are doing local, it does some whacky stuff and the variable is presumably named getfenv instead of calling it.

So I would recommend just putting it a table, where you know the behavior (also, it is a BAD idea to populate the global namespace with some random variables, people reading your code will be soo confused).

Hope this helps!

2 Likes