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

How do I cycle through a Table?

I've got a teleport script with several destinations. How would I cycle through the table when I press a button to get to the next selection?

Ex.

local Destinations = {
	["House"] = Vector3.new(10,20,10);
	["Street"] = Vector3.new(10,10,40);
	["Office Building"] = Vector3.new(190,5,440);
}

1 comment

0

You should research "for i,v in pairs"

1 answer

Generally you would want to use numerical indices for something like this, but in order to do it with what you have, you could create a new table with the indices of the first, and use that to cycle through it:

local Destinations = {
    ["House"] = Vector3.new(10,20,10);
    ["Street"] = Vector3.new(10,10,40);
    ["Office Building"] = Vector3.new(190,5,440);
}
local indices = {};
local current = 0;

for i in next, Destinations do
	indices[#indices + 1] = i;
end;
local function cycle()
	current = (current < #indices) and current + 1 or 1;
	return Destinations[indices[current]];
end;

Read more about: For loops and the ternary operator.

Hope this helped.

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