Hey there, so I was wanting to make a color block game just for fun so I could see how it worked, but I ran into a problem. I didn’t know how I could pick out a random item from my dictionary.
Basically I have different keys that are the colors and equal a Color rgb value.
local RandomColors = {
["Red"] = Color3.fromRGB(255, 0, 0);
["Blue"] = Color3.fromRGB(0, 115, 255);
["Black"] = Color3.fromRGB(0, 0, 0);
["White"] = Color3.fromRGB(255,255,255);
["Grey"] = Color3.fromRGB(99, 99, 99);
["Orange"] = Color3.fromRGB(255, 140, 8);
["Purple"] = Color3.fromRGB(179, 2, 255);
["Green"] = Color3.fromRGB(46, 255, 0)
}
local randomColor -- Here, I'm trying to set up the variable for my random color, but I'm having trouble figuring out what to do.
print(randomColor)
I need to get a random Color from the dictionary, so I can control other things in the game
You would probably have to make an array containing just the keys.
local keys = {}
for k, _ in pairs(RandomColors) do
table.insert(keys, k)
end
local randomKey = keys[math.random(#keys)]
print(randomKey) -- "Red", "Blue", etc.
local randomColor = RancomColors[randomKey]
print(randomColor) -- the color3
The issue is that you can’t really use numerical indices on dictionaries, so one thing you could do is work around that by making a table of your keys and then randomize a value from that table, like this:
local RandomColors = {
["Red"] = Color3.fromRGB(255, 0, 0);
["Blue"] = Color3.fromRGB(0, 115, 255);
["Black"] = Color3.fromRGB(0, 0, 0);
["White"] = Color3.fromRGB(255,255,255);
["Grey"] = Color3.fromRGB(99, 99, 99);
["Orange"] = Color3.fromRGB(255, 140, 8);
["Purple"] = Color3.fromRGB(179, 2, 255);
["Green"] = Color3.fromRGB(46, 255, 0)
}
local colorTable = {}
for key,_ in pairs(RandomColors) do
table.insert(key)
end
local randomKey = colorTable[math.random(1,#ColorTable)]
local randomColor = RandomColors[randomKey]
print(randomColor)