A code for HEX code converting, feedback?

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

There are a couple things that could be improved. Since your module is just a table of functions, you’d define and call the HexToColor3 and Color3ToHex functions with a . instead of a :.

Next, you can use Lua’s built in string.format pattern. Here’s the Roblox page on that. Strings | Documentation - Roblox Creator Hub

Basically, you don’t need to use helper functions or char lists, and can do something like this:

function M.Color3ToHex(C3)
    return string.format('%02x%02x%02x', C3.R, C3.G, C3.B)
end

For your conversions from hex to Color3, you can do basically the opposite. Lua also has a built in tonumber(str, radix) function, so you don’t need to search a list for it. You could just get your numbers by sub-stringing the hex string and then calling tonumber(sub, 16) on each color section.

The initial code is a nice solution, but it’s also worth it to look into things Lua has built in.

3 Likes