Recently i made a code to convert from HEX code to RGB and vice-versa
But i don’t know if it’s good enough, so i’m posting it here so someone can judge it
This is my first post in this topic btw
local M = {}
local floor = math.floor
M.HexCharsList = {
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
"A",
"B",
"C",
"D",
"E",
"F"
}
function CharToNum(Char) Char = string.upper(Char)
for Index, Value in ipairs(M.HexCharsList) do
if tostring(Value) == Char then
return Index-1
end
end
end
function NumToChar(Num)
return M.HexCharsList[Num+1]
end
function M:HexToColor3(Hex)
Hex = tostring(Hex)
local R, G, B
if (#Hex ~= 6) then
if (#Hex ~= 7) and string.gsub(Hex, 1, 1) ~= "#" then
error("Invalid HEX length")
else
Hex = string.sub(Hex, 2, #Hex)
end
end
for L = 1, 5, 2 do
local Maj = CharToNum(string.sub(Hex, L, L))
local Min = CharToNum(string.sub(Hex, L+1, L+1))
local Val = Maj*16+Min
if L == 1 then R = Val end
if L == 3 then G = Val end
if L == 5 then B = Val end
end
return Color3.fromRGB(R, G, B)
end
function M:Color3ToHex(C3)
local R = floor(C3.R*255)
local G = floor(C3.G*255)
local B = floor(C3.B*255)
local Hex = ""
local function VF(Num)
Num = floor(Num)
local Div = Num/16
local Maj = floor(Div)
local Min = (Div-Maj)*16
Hex = Hex .. NumToChar(Maj) .. NumToChar(Min)
end
VF(R) VF(G) VF(B)
return Hex
end
return M