How to get the position of something in a table based off the value?

Here is what I am trying to do:

module.SearchTable = function(Table,ObjectToFind)
	for i,v in pairs(Table) do
		if v == obj then
			return i[v]
		end
	end
end

Would this return the position of it in the table? Im not sure so I though Id ask.

Example of my use case:

local NPCs = {workspace.NPC,workspace.NPC2}

local newNpc = NPC3:Clone()
newNpc.Parent = workspace

table.insert(NPCs,(#NPCs + 1),newNpc)

local tablePosition = module.Search(NPCs, newNPC)

I could have a number of NPCs in that table, it isn’t limited to 3. This is why if I add multiple at once, I want to be able to get its position in the table (i.e NPCs[1], NPCs[2])

1 Like

NPCs[1].HumanoidRootPart.Position i think, If that what you were asking

Im looking for the position of something in a table.

I want the function to return something like:
NPCs[1]
or
NPCs[2]
or whatever “spot” it is in the table.

Use table.find(array, valueToFind), it returns the position of the found value, or nil if nothing’s found. Keep in mind that it’s faster than using lua to find a value in a table, and it only works on arrays.

2 Likes

Oh, awesome! So this should return something like NPCs[PositionInArray]? I’ll make sure to test this once Im finished with online classes, thanks a ton.

Yeah, as long as the value is in the array it should.

1 Like