Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Creating different variables using a for loop?

So, I'm wondering if it's possible some how to create different variables each time a for loop runs. What I have is an array whose values are tables, listed in a certain order. What I'm trying to do is run through the array, and assign each table to a respective variable.

I know about using multiple assignment, however I don't know how many tables will be in the array when I need to create the variables. The other problem arises when creating the variable name, as (to my knowledge) variables cannot have concatenation in them, or any special operators. Thus I cannot make individual variables whose names correspond with their respectable value, or table in the array.

for i, v in pairs(PlayerScores)do
	player..i = PlayerScores[v] -- The variable 'player..i' would be player1 for table 1 in the array, and player2 for table 2, and so on. 
end

Is there any way to do this? I can't create the variables individually, as the amount of tables(amount of players), may be fewer than variables I'm assigning. So I'd error out.

Any help is appreciated, and if anything needs clarification please let me know. Thanks! :)

1 comment

0

Would you be able to store them in a table e.g. [player..i] = PlayerScores[v] or have i got the wrong idea lol

2 answers

More tables. You're literally dealing with a key/value pair here - Instead of trying to make a variable with that name, make a table with a key for that name.

You should use tables as eLunate said, but it is indeed possible to do that

PlayerScores = {23, 38, 90, 72}

do
	local env = getfenv(0)
	for i, v in pairs(PlayerScores) do
		env["player"..i] = v
	end
end

print(player1, player3)

23 90

Anyway, that is kinda hacky and you should avoid doing that.

This discussion is preserved as it was. New answers, comments, and votes are closed.