Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I cycle through a Table?

Asked by 8 years ago

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);
}
0
You should research "for i,v in pairs" iGlaciem 72 — 8y

1 answer

Log in to vote
1
Answered by
Pyrondon 2089 Game Jam Winner Moderation Voter Community Moderator
8 years ago

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.

Ad

Answer this question