✓ Accepted answer
As hiimgoodpack says, "#" doesn't work on dictionaries because it only counts array elements.
One option is to manually count the keys and select a random one based on that, like this function does:
function PickRandomKeyFromDict(d)
local n = 0
for _, _ in pairs(d) do
n = n + 1
end
n = n - math.random(1, n)
for k, _ in pairs(d) do
if n == 0 then return k end
n = n - 1
end
end
You could use it like this:
local quoteKey = PickRandomKeyFromDict(Dict)
local quoteValue = Dict[quoteKey]
However, you probably don't need quoteKey and could have all this work better as a list:
local quotes = {
{Text = "What's up", Color = BrickColor.new("Lime green").Color},
{Text = ""yoooooo", Color = BrickColor.new("Lapis").Color},
--etc
}
--Get random quote by doing:
local quote = quotes[math.random(1, #quotes)]
--can now do quote.Text and quote.Color
In either case, don't forget to initialize the randomseed at the top of your script: math.randomseed(tick()); math.random() (you need to skip the first math.random for superior results). You're only supposed to initialize the randomseed once, not multiple times in a loop. (There do exist reasons for initializing it multiple times, but in your case once is better so that you can get a new quote whenever you want and it will still seem random.)
3 comments
Dictionaries dont work with the # system to get the number of keys.
Why do you want to use a dictionary in the first place? Judging from how you're using it, It seems like an array would do you fine.
Good point. I don't really like dictionaries because I have to make sure I spell my keys right.