What math. function is it to operate a table in order?

So I’m making a table of 4 colors but I want it to do in order

local colors = {
		Color3.fromRGB(0, 137, 207);
		Color3.fromRGB(196, 40, 28);
Color3.fromRGB(0,255,0);
Color3.fromRGB(0,0,0);
	}
	
while true do
		local color = colors[math.random(1,#colors)] -- I can't think of any math function to make it in order so I'll stick with .random until I find an answer in the post..
		script.Parent.Color = color
		wait(1)
	end

Not sure that I understand, in what order? You’re selecting a random place in the table here.
Do you want it to be the first color, then the next time it runs, the second color?
Or just a random color as you’re doing here.

If you want it 1 by 1, just create a variable that is equal to 1.
And increase it every time in thewhile loop until it reaches the table length.
And color is the table with the place of the variable.

For example:

local colors = {
--Imagine I had 6 colors in here.
}
local index = 1
while true do
	local color = colors[index] --Table in the place of the index
	script.Parent.Color = color --Set the color
	if index == #colors then --If it reached the table length
		index = 1 --Set it back to 1
	else
		index = index + 1 --If not, increase it by 1
	end
	wait(1)
end
--It'll go in the colors 1 by 1 and start again when finished
1 Like

In this situation, we would use a for loop to loop through the colors in any order you like.

I recommend learning or skimming through a roblox lua tutorial in order to obtain knowledge of where these tools are to help you for your purposes.

1 Like

Actually inside the while loop, you can do another ipairs loop for looping through all the colors, so it iterates through all the colors.

1 Like

Yeah 1 by 1, in order so the colors start at the top of the table and then down

1 Like

So you want that after they go up, they go down?

I changed my example a bit to work like that:

local colors = {
--Imagine I had 6 colors in here.
}
local index = 1
local up = true
while true do
	local color = colors[index] --Table in the place of the index
	script.Parent.Color = color --Set the color
	if up then --If up is true
		index = index + 1 --Increase the index
	else
		index = index - 1 --Decrease the index
	end
	if index == #colors then --If it reached the table length
		up = false --Make it go down
	elseif index == 1 then
		up = true --Make it go up
	end
	
	wait(1)
end
--It'll go in the colors 1 by 1 and go back when finished

Is this what you need?

no, it keeps looping starting from top to bottom of the table

1 Like

Is this one going back to the start of the table? Are you sure?

1 Like

Thanks for the help, I’m not really familiar with tables yet but i learned a bit from this code you wrote, thanks again and have a great day

1 Like