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

How to find position of an item in table?

Hey there.

Trying to scroll through table 'F' in my script

local E = A:WaitForChild('C'):WaitForChild('H')
local F = {"your","my","we","yeet",}

for x123,x124 in pairs(F) do
	if E.Text == x124 then
		E.Text = F[x123 + 1]
	end
end

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

repeat
for nn = 0,1,0.05 do
	E.TextTransparency = nn
	wait(.05)
end

local abcd = #F
	for a,b in pairs(F) do
		if E.Text == b then
			local function yeet1()
				if b == #F then
					return 1
				else
					return b + 1
				end
			end
			print(tostring(F[tonumber(yeet1)]))
		end
	end
for mm = 1,0,-0.05 do
	E.TextTransparency = mm
	wait(.05)
end
until 1 == 2

while wait() do
	for zz = 0,1,0.01 do 
		wait(.05)
		E.TextColor3 = Color3.fromHSV(i,1,1)
	end
end

2 answers

✓ Accepted answer

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

local E = "your"
local F = {"your","my","we","yeet",}

for x123,x124 in ipairs(F) do
    if E == x124 then
        E = F[x123 + 1]
		print("Matched at: " .. x123 .. " with " .. tostring(E) .. " and " .. tostring(x124))	
	else
		print("No match: " .. x123)	
    end
end

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

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

local function LinearSearch(TargetTable, TargetValue)
	for Key, Value in pairs(TargetTable) do
		if Value == TargetValue then
			return Key
		end
	end
end

local TargetTable = {"a", "b", "c"}
print(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.

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