This should choose a random one from a list of 8 keys (Colors) and their values (BrickColor) but only return the key name (Which should be a string of the color chosen).
Currently the only problem is that this returns "nil" and probably not the right way to do it since I've just begun working with tables/dictionaries.
local color = {} local colorDictionary = { ["Red"] = BrickColor.new("Bright red"); --[[Should choose 1 out of the 8 but also return the key, (Return "Red" and not "BrickColor.new("Bright red")]] ["Orange"] = BrickColor.new("Bright orange"); ["Yellow"] = BrickColor.new("Bright yelow"); ["Green"] = BrickColor.new("Bright green"); ["Blue"] = BrickColor.new("Bright blue"); ["Pink"] = BrickColor.new("Pink"); ["Brown"] = BrickColor.new("Brown"); ["White"] = BrickColor.new("Lily white") }; function color.randomColor() local randomColor = colorDictionary[math.random(0, #colorDictionary)] --weird error if 0 was a 1 print(randomColor) --prints nil so obviously not correct end return color
I read up on wiki that this code would probably print the value instead of the key. So because it's like that I wanted to see if printing the value worked. Any way I can change this for the key?
Because you're using a Dictionary and not an Array, the colorDictionary[math.random(0, #colorDictionary)]
always returns colorDictionary[0]
, which is nil
.
This also explains your incorrect bounds error, because math.random(1, 0)
errors, and #colorDictionary
resolves to 0.
There are several ways to fix this, but the easiest is to restructure your Table:
local color = {} local colorDictionary = { {"Red", BrickColor.new("Bright red")}; {"Orange", BrickColor.new("Bright orange")}; {"Yellow", BrickColor.new("Bright yelow")}; {"Green", BrickColor.new("Bright green")}; {"Blue", BrickColor.new("Bright blue")}; {"Pink", BrickColor.new("Pink")}; {"Brown", BrickColor.new("Brown")}; {"White", BrickColor.new("Lily white")} }; function color.randomColor() local randomColor = colorDictionary[math.random(0, #colorDictionary)] print(randomColor[1]) end return color
You could even make the sub-tables dictionaries rather than arrays to give the attributes explicit names, like ColorName or BrickColor, but I'll leave that to you.