Find the value of a position in a table

Hello!

I am currently writing a module to grab a random selection from a dictionary. How it will work is take the value of the entry of the table, assign it to a tool, and then pass it onto the player.

However, I am uncertain of how to find which object occupies a specific position in a table from using table.find(). The second parameter of table.find is the value of the position but I don’t want to find the value, and instead want to use the third parameter of the function.

How can I find the position of an entry based on number position and not based on value?

You would use table[position], like so:

local t = {"Hello", "Goodbye", "Hi"}

print(t[2]) --> "Goodbye"

If you already have the position though???

I’m sorry! My wording was confusing.

I’m trying to find the value of a random position in the table. Let’s say there were two entries, A and B. If I were to randomize a number and pull 1, it would return A, and if it pulled 2, it would return B.

My apologies.

Tbh you still said the same thing. Maybe a code analogy would work better here?

-- Table variable
local tab = {
"A"
"B"
"C"
}

local position = math.random(1, #tab) 
if position == 1 then
    -- return A, as it is the first entry
if position == 2 then
    -- return B, as it is the second entry
etc.

This would work normally, however I want it to be flexible based on the amount of table entries there are. Sorry for being confusing previously.

And may I ask what the point of this is. Hardcoding each case is not a good idea and you’re better off doing return tab[math.random(#tab)]

You just gave me the answer LOL. Thank you!

My previous replies were bad examples. I only hardcoded each case as I didn’t know exactly how to say it, so I just duplicated the if statement.