Change variables by using for loop?

So let’s say we have 3 variables here:

local apple1 = nil
local apple2 = nil
local apple3 = nil

Let’s say I want to change apple1 to 1, apple2 to 2 and apple3 to 3 by using a for loop, how do I reach the variable?

The code below only works for strings.

for i = 1,3 do
	"apple"..i = i

To make something like this, since you shouldn’t really access a variable via a string, you should instead put them in tables and use something along the lines of:

local apples = {apple1 = nil, apple2 = nil, apple3 = nil}

for i = 1,#apples do
   apples[i] = i

Instead of indexing them through individual variables, you are indexing them through a table which should work smoothly. This method becomes a lot more useful when instead of using for i =, you start using for i,v in pairs loops.

for i,v in pairs(apples) 
if v = nil then
v = i

Thanks! Actually using this with humanoid:LoadAnimation, and it works perfectly fine.

1 Like

Just for completeness, to answer the original question…

You can’t actually change local variables, but you can change global ones by getting the environment of the current script thread and changing the variables through that.

-- Notice that these variables are no longer local
apple1 = nil
apple2 = nil
apple3 = nil

local env = getfenv() -- Get environment of current script thread

for i = 1,3 do
	env["apple"..i] = i -- Change environment values

print(apple1) --> 1
print(apple2) --> 2
print(apple3) --> 3

Regardless of the ability to do this, it makes much more sense to store their values in a dictionary as @K_ngTMB pointed out (although the code provided is inaccurate).


Yeah, I made a few typos, was in a bit of a rush.