How do I find a value using another value from a dictionary in a script?

Hello! I’m trying to make it so in a script, if you have a value in this case a color3 value, it will find the name of the color in the dictionary. Example: Lets say you have a color3 value like 255, 0, 0, I’d like to find the name of it “Red” from the dictionary, how would I do that in a script?

-- Module script

local colors = {
	{colorname = "Red", colorvalue = Color3.fromRGB(255, 0, 0)},
	{colorname = "Green", colorvalue = Color3.fromRGB(0, 255, 0)},
	{colorname = "Blue", colorvalue = Color3.fromRGB(0, 0, 255)},
	{colorname = "Brown", colorvalue = Color3.fromRGB(175, 85,0)},
	{colorname = "White", colorvalue = Color3.fromRGB(255,255,255)},
	{colorname = "Black", colorvalue = Color3.fromRGB(0,0,0)},
	{colorname = "Yellow", colorvalue = Color3.fromRGB(255,255,0)},
	{colorname = "Pink", colorvalue = Color3.fromRGB(255,0,255)},
	{colorname = "Cyan", colorvalue = Color3.fromRGB(0, 255, 255)}
}

return colors

Loop through the dictionary and check if the value is (255, 0, 0). If it is, return its name.

The way you would handle that depends on the way your table is structured, but for your specific use-case, you would loop through the colors table and search for any value that matches what you’re looking for.

local function find(t, value)
   for _, v in t do -- loop through the provided table
       -- the underscore is the index of the inner-tables of the list
       -- the 'v' is the actual inner-table itself (i.e "{colorname = "Green"}")
       for _, data in v do -- this loops through the table that holds the colorname and color3 values
           -- 'data' is the value of each specific key listed in the 'v' table
           if data == value then -- this checks if the value of the key matches what you're looking for
               return v -- this returns the table that the key is in
           end
       end
   end
end

local info = find(colors, "Red") --> returns the table that has "Red" in it
print(info.colorname) --> prints "Red"
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.