How to get index from a table value

This sounds very confusing at first, and to be honest I’m not sure if it’s even possible to do.

this sets up a function, basic randomizer

function randomizer(yourTable)
	local n = math.random(1, #yourTable)
	local thing = yourTable[n]
	return thing
end

this script utilizes that and tries to basically set A to a random thing from the table, and remove the result from the table after it is chosen (to prevent duplicates, you know)

local positionTables = {Vector3.new(0,0,64), Vector3.new(0,0,-64), Vector3.new(64,0,0), Vector3.new(-64,0,0)}

	local A = randomizer(positionTables)
	table.remove(positionTables, A) --erroring line

on the erroring line, it is quite obvious- im giving it a vector3 instead of a number, being its position and all

so my question is, how can i get the index from an array value (the vector3)?

table.find returns the index. It returns nil if nothing is found.
IIRC, it only works on arrays, and they must not be cut off, have any gaps, etc.

If you want a function for ANY index, this works:

local function TableFindIndexFromValue(tbl, v)
    for index, value in pairs(tbl) do
        if value == v then
            return true
        end
    end
    return false
end

But use table.find on arrays, as it’s faster.

3 Likes

i believe the second argument for table.remove is asking for the index of the table instead of the value

yes i know which is why im trying to find the index from the value

what does that mean? i understand all the other stuff but…?

oh yeah you can use table.find in the second argument of table.remove

For example:

local array = {
    1,
    2,
    3,
    4,
    5
}

array[3] = nil
-- Now, the index 3 is the gap in the array. table.remove re shifts everything to remove that gap, so you shouldn't have any issues.

-- Also,
-- #array == 2 because that's the "highest index", that has no gap until it