Table.find, help

  1. What do you want to achieve?
    i wanna use table find
  2. What is the issue? Include screenshots / videos if possible!
    not work
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    idk how to get the index of a table without using table.find

So, I tried using table.find after changing the index, but it doesn’t update it and just returns nil

(simple code of what i want to try:)

local mytable = {"Value1"}
local pos = 1

part = game.Workspace.Part

part.ClickDetector.MouseClick:Connect(function()
	local index = table.find(mytable, "Value1")
	if index then
		
		local value = mytable[index]
		table.remove(mytable, index)
		table.insert(mytable, pos, value)
		
		pos +=1
		
	end
	
end)


task.spawn(function()
	while wait(3) do
		print(table.find(mytable, "Value1"), mytable)
	end
end)

output:

1 ; [1] = "Value1"
--After click
nil ; [2] = "Value1"
local mytable = {"Value1"}
local pos = 1

part = game.Workspace.Part

part.ClickDetector.MouseClick:Connect(function()
	local index = table.find(mytable, "Value1")
	if index then
		local value = mytable[index]
		table.remove(mytable, index)
		
		if pos > #mytable + 1 then
			pos = #mytable + 1
		end
		
		table.insert(mytable, pos, value)
		pos += 1
	end
end)

task.spawn(function()
	while wait(3) do
		print(table.find(mytable, "Value1"), mytable)
	end
end)

table.find searches an array starting at index 1 (or another number if you provided it), and increments until the specified value is found or the value is nil.

The reason it doesn’t work is because when the part is clicked, the index of "Value1" gets incremented to 2, and the value at index 1 is removed. This turns the array into a dictionary. When you use table.find afterwards, it sees that the value at index 1 is nil and stops.

Here is an alternative to table.find that works with dictionaries.

function FindInTable(Table, ValueToSearch)
	for Key, Value in pairs(Table) do
		if Value == ValueToSearch then
			return Key
		end
	end
end
1 Like