How can I pick a random item from my dictionary

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

2 Likes

local randomColor = RandomColors[math.random(1, #RandomColors)]

I believe this is how though I have never tried it with a dictionary like this.

Instead of have the names maybe add numbers then do math.random(1,MaxNumber). You can use comments so you know what colour is which when editing.

Example:
[1] = Color3.fromRGB(255, 0, 0);

Right. I did that, but it stated that argument #2 was missing, so I thought something else was wrong. Let me try again.

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
6 Likes

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)

^just like what @blokav said

6 Likes

Thanks a lot for helping out, I’ll keep you updated on any additional issues!