Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I get the position of a table?

Asked by
Loot_O 42
4 years ago

Now, I'll explain here. A while ago, I figured out how to make it so that it chooses a random item inside a table, but I want to know what place it is in. Still confused? Here's some code that I made.

local testing = {"Hello world!", "Hi!", "Greetings!"}
local r = testing[math.random(1, #testing)]

print(r)

Now say this would pick the second item in the table ("Hi!"). Now it would print what the string says, but I want it to print on what place the table is on. What I mean by that is in that example, it is on the 2nd item in the table. Basically, I want to figure out how to get the place the random item picker is on.

1 answer

Log in to vote
1
Answered by 4 years ago

Just make a variable:

local index = math.random(1,#testing)

And replace the variable local r with:

local r = testing[index]

The location of the value is what we call the index, and you can define it with one variable.

Your final code is this:

local testing = {"Hello world!", "Hi!", "Greetings!"}
local index = math.random(1,#testing)
local r = testing[index]

print(r)
print(index)
0
thanks! Loot_O 42 — 4y
0
np CrypxticDoge 135 — 4y
0
Or: table.find(testing, r) Ziffixture 6913 — 4y
Ad

Answer this question