I'm attempting to solve one of my previous queries and in order to have a breakthrough all I need to know is if it's possible to search through an entire table and store a random key within a variable while ignoring it's number values.
For example using this table I would like to randomly output one of the dictionary names such as Apples or Cabbages (quotations if possible) but NOT its number values.
Is this possible with tables or should I use a seperate modified table or array?
01 | ExampleTable = { |
02 | [ "Apples" ] = 0 , |
03 | [ "Berries" ] = 32 , |
04 | [ "Cabbages" ] = 5 , |
05 | [ "Daikons" ] = 89 , |
06 | [ "Eggs" ] = 9 |
07 | } |
08 |
09 | RandomKeySelector = |
10 |
11 | print ( "The random food item is" ,RandomKeySelector) |
For get a Random key from dictionary table you need to create a array table with index of all elements of your dictionary table, For example:
01 | local dictionary = { |
02 | [ "Eggs" ] = 10 , |
03 | [ "Apples" ] = 50 |
04 | } |
05 |
06 | local function GenerateRandom() |
07 | --> You need to create a fake array table. |
08 | local Array = { } |
09 |
10 | for index in pairs (dictionary) do |
11 | table.insert(Array, index) --> Insert the index to array table |
12 | end |
13 |
14 | --> After that only get the random number from array table. |
15 | local RandomNumber = math.random( 1 , #Array) --> Will get a random number of array |
Basically, i created a fake array table, added the index of the dictionary table, after that i generated the random value.
Fixed script:
01 | local ExampleTable = { |
02 | [ "Apples" ] = 0 , |
03 | [ "Berries" ] = 32 , |
04 | [ "Cabbages" ] = 5 , |
05 | [ "Daikons" ] = 89 , |
06 | [ "Eggs" ] = 9 |
07 | } |
08 |
09 | local function GenerateRandomIndex() |
10 | local Array = { } |
11 |
12 | for index in pairs (ExampleTable) do |
13 | table.insert(Array, index) |
14 | end |
15 |
You want to use math.random()
. Set the first argument to 1 and the next to #ExampleTable. The hashtag means it will get the length. If there were 5 items in the table, it would be 1, 5.
But from my understanding of tables like this in the past, I had to put another table inside of the table because you can't get the name if the key has brackets around it.
01 | ExampleTable = { |
02 | { Name = "Apples" ,Number = 0 } , |
03 | { Name = "Barries" ,Number = 32 } , |
04 | { Name = "Cabbages" ,Number = 5 } , |
05 | { Name = "Diakons" ,Number = 89 } , |
06 | { Name = "Eggs" ,Number = 9 } |
07 | } |
08 | print (#ExampleTable) |
09 | local numberPosition = math.random( 1 , #ExampleTable) |
10 | RandomKeySelector = ExampleTable [ numberPosition ] .Name |
11 |
12 | print ( "The random food item is " ,RandomKeySelector) |