Whether you’re trying to store colors in your data stores efficiently,
ColorStore:SetAsync("0, 0, 255")
or using RichText to color parts of your text,
'<font color="rgb(127, 0, 255)">GFink: </font>Hello world!'
you find yourself needing to convert a Color3 value to an RGB string value.
You’re trying to do this: Color3.new(0.5, 0, 1)
→ "127, 0, 255"
Conversely, if you’re loading that RGB string value from a data store, or trying to extract the Color3 value out of a RichText string with colored text, you will need to convert that string value into an Color3 value.
That’s just the inverse operation: "127, 0, 255"
→ Color3.new(0.5, 0, 1)
If you look around for an easy way to do these operations, you stumble upon help threads with solutions that look like this:
That’s all well and good as long as they work, but to me it just looks a bit wordy/repetitive. You gotta repeat yourself three times for the three RGB channels.
Here is a Color3
→ RGB string
function which does the same thing as the verbose functions, but doesn’t repeat itself:
local function Color3toRGBstring(color3)
return string.gsub("R,G,B", "%u", function(channel)
return tostring(math.round(color3[channel] * 255))
end)
end
Sidenote: coincidentally, %u would also be appropriate here if this operation was done using the triple string.format substitutions — string.format("%u, %u, %u", tostring(math.round(etc * 255)), etc..)
where %u here signifies positive integers
Here is a single-line RGB string
→ Color3
function which also doesn’t repeat itself:
local function RGBstringToColor3(RGBstring)
return Color3.fromRGB(unpack(string.split(RGBstring)))
end
Luckily, the messy "255 ", "127 " strings with spaces automatically get converted to numbers during the fromRGB
operation
That second function is courtesy of @D0RYU:
Roblox uses split.string
with the comma as a separator by default, so we can make ours even shorter :^)
If you have a way of simplifying these functions even further, that would be very cool to see, so please respond!