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

Help with tables?

Asked by 10 years ago

How would I move to the next item in a table with the click of a GUI? ex;

1local table = {'hi', 'there'}
2 
3script.Parent.MouseButton1Click:connect(function()
4    print(table[1])
5end)

when you click, how would I move from the value 'hi' to the next value 'there'?

1 answer

Log in to vote
1
Answered by
TaslemGuy 211 Moderation Voter
10 years ago

You'll need a variable to keep track of where you currently are. We'll call it index since it's the index in the table we want to look at.

1local table = {'hi', 'there', 'this', 'is', 'a', 'message'}
2 
3local index = 1
4 
5script.Parent.MouseButton1Click:connect(function()
6    print(table[index])
7 
8    index = index + 1
9end)

However, there's something not quite right here. Once index gets to the end of the table, you'll be indexing something outside its range! Therefore we need to decide what to do in the case. The easiest method is probably to just start back at the beginning:

01local table = {'hi', 'there', 'this', 'is', 'a', 'message'}
02 
03local index = 1
04 
05script.Parent.MouseButton1Click:connect(function()
06    print(table[index])
07 
08    index = index + 1
09 
10    if index > #table then
11        index = 1
12    end
13end)
Ad

Answer this question