Hey,
so basically I’m new to dictionaries and tables and I ran into a problem with them So what is it the easiest wat for getting a random item from the dictionary:
Here is the dictionary:
}
I tryed flowers.commons[math.rad(0,3)] but it seams to return nil.
Is it any way to get random item from commons or if should I make it different so it will work.
Thanks
math.rad doesn’t get you a random number, but you can use Random to do that. You’ll need to set the Random seed at the start of your script so it’s properly random, but you were pretty close with your method.
The previous method was math.random, but this has some flaws which using Random solves.
local randomGen = Random.new()
(your other code here)
flowers.commons[randomGen:NextInteger(0,3)]
Ah, how convenient. I actually have a library that contains a random key selector for a dictionary. It does what DataErased suggested but invisibly so that you don’t have to make both the dictionary and the array part yourself.
My handy function, DictionarySelectRandom, accounts for arbitrary dictionaries so all you have to worry about is writing out the dictionary. A table of keys will automatically be created and fetched from internally. You just lose the benefit of consistent seeded results as a new Random object is generated each time.
I would avoid metatables if you don’t actually need them.
I decided not to do anything about consistent random objects mostly for the sake of interruptions (a global Random would just be the equivalent of math.random and share pseudorandom results cycles where not desired and keeping it the same would change the requirements altogether).
If you’d like to discuss my specific implementation in more detail, feel free to shoot me a PM. I had a Code Review topic on it earlier, so I’d absolutely love to hear any feedback about it.