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

How to find position of an item in table?

Asked by 7 years ago
Edited 7 years ago

Hey there.

Trying to scroll through table 'F' in my script

1local E = A:WaitForChild('C'):WaitForChild('H')
2local F = {"your","my","we","yeet",}
3 
4for x123,x124 in pairs(F) do
5    if E.Text == x124 then
6        E.Text = F[x123 + 1]
7    end
8end

I plan to put this in a repeat to run it over and over again, where it fades in and shows the next message, then fades out and shows the next one

I thought where I put ``E.Text = F[x123 + 1] it would make E.Text equal to F[2], since x123 is one at the moment.

Where am I wrong

EDIT:

I updated my code to this, but I get 'nil' - you also get some bonus content

01repeat
02for nn = 0,1,0.05 do
03    E.TextTransparency = nn
04    wait(.05)
05end
06 
07local abcd = #F
08    for a,b in pairs(F) do
09        if E.Text == b then
10            local function yeet1()
11                if b == #F then
12                    return 1
13                else
14                    return b + 1
15                end
View all 31 lines...

2 answers

Log in to vote
1
Answered by 7 years ago

You're not wrong. It's printing as expected. Also, I'm using ipairs because your order when going through the table might be different than mine. With ipairs it'll iterate in order.

You're already finding the positions of items in the table with x123

01local E = "your"
02local F = {"your","my","we","yeet",}
03 
04for x123,x124 in ipairs(F) do
05    if E == x124 then
06        E = F[x123 + 1]
07        print("Matched at: " .. x123 .. " with " .. tostring(E) .. " and " .. tostring(x124))  
08    else
09        print("No match: " .. x123)
10    end
11end

My results:

Matched at 1 with my and your

Matched at 2 with we and my

Matched at 3 with yeet and we

Matched at 4 with nil and yeet

At index 1 it matched "your" to "your" so E becomes "my"

At index 2 it matched "my" to "my" so E becomes "we" and so on

Ad
Log in to vote
1
Answered by
Avigant 2374 Moderation Voter Community Moderator
7 years ago
Edited 7 years ago

To find the key of an arbitrary value in a table, we can use linear search:

01local function LinearSearch(TargetTable, TargetValue)
02    for Key, Value in pairs(TargetTable) do
03        if Value == TargetValue then
04            return Key
05        end
06    end
07end
08 
09local TargetTable = {"a", "b", "c"}
10print(LinearSearch(TargetTable, "b")) --> 2

With linear search, the number of possible steps we have to take through the table in the worst case (value is at the last element iterated over in the table) increases linearly with the growth of the number of elements in a table.

Answer this question