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

Help with tables?

Asked by 9 years ago

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

local table = {'hi', 'there'}

script.Parent.MouseButton1Click:connect(function()
    print(table[1])
end)

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
9 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.

local table = {'hi', 'there', 'this', 'is', 'a', 'message'}

local index = 1

script.Parent.MouseButton1Click:connect(function()
    print(table[index])

    index = index + 1
end)

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:

local table = {'hi', 'there', 'this', 'is', 'a', 'message'}

local index = 1

script.Parent.MouseButton1Click:connect(function()
    print(table[index])

    index = index + 1

    if index > #table then
        index = 1
    end
end)

Ad

Answer this question