I can’t seem to find any info on this, but is there a way to convert RGB to HEX values? I want to do this as I am currently having to save RGB values as individual values, and this takes up a lot of characters, while HEX would only take up 6 characters, for data stores
I don’t believe it’s possible to use HEX instead of RGB, you can use a rgb to hex converter online if you need to translate them.
So, there’s a few ways to do what you want to do. Conversion to hexadecimal is a bit wonky in lua imo, but, something like this is generally what I use for hexadecimal conversion.
Another way to think about this is just to treat the Color3 like three bytes. Datastores can safely store 7 bits, so up to 127, so, an easy way (which won’t effect efficiency and will get you 6 bytes however you do it, this technically isn’t the “best” way but its relatively easy) is to store string.char(math.min(red, 127)) .. math.max(math.max(red - 127, 0) .. otherColors
. Then to get the color back, you take the first two byte values and add them up, then the next two, etc.
The last, and generally “best” (in most people’s opinions at least) is to store the colors in a 24 bit number. Numbers in Roblox can support integers up to 24 bits fine, so, you can store a whole Color3 in one number. It takes more space this way, obviously, but, you can represent it as a 24 bit number, and store it as bytes. You’ll again (For datastores) get 6 bytes, but its a more “proper” way to go about it.
Lastly (this won’t be datastore safe on its own!!), with the newly introduced string.pack
and string.unpack
functions you can simplify the above option even more, by simply using local binary = string.pack("I3", red, green, blue)
, and local red, green, blue = string.unpack("BBB", colorString)
. Basically what this does (and is now what I’d personally consider to be the absolute best method) is it takes your three input bytes, and turns them into a 3 byte unsigned integer basically in binary form (see these docs, the devhub docs are not ready yet afaik). The unpack part takes your packed color string and will turn it right back into three individual bytes. In short, this method is the above, except lua does it for you instead of botching some epic code together to create 24 bit integers
Its true that you can’t use hexadecimal directly e.g. some sort of Color3.fromHex function, but, conversion from hex to RGB is 100% possible in lua, it’s just undesirably hard.