It is currently March 29th, 2024, 2:13 am

Color Code Parser

Discuss the use of Lua in Script measures.
User avatar
Kaelri
Developer
Posts: 1721
Joined: July 25th, 2009, 4:47 am

Color Code Parser

Post by Kaelri »

I thought some people might find this useful. This is a function that will take any Rainmeter color code and output a table with the red, green, blue and alpha as separate values. (If no alpha is given, the function provides "255" automatically.)

Code: Select all

function ParseColorCode(String)
	local Colors = {}

	for a in string.gmatch(String, '[%a%d]+') do
		table.insert(Colors, a)
	end

	if #Colors == 1 then
		local Hex = table.remove(Colors, 1)
		for a in string.gmatch(Hex, '[%a%d][%a%d]') do
			a = tonumber(a, 16)
			table.insert(Colors, a)
		end
	else
		for i,v in ipairs(Colors) do
			v = tonumber(v)
		end
	end

	if #Colors == 3 then
		table.insert(Colors, 255)
	end

	return Colors
end
Examples:

Code: Select all

ParseColorCode('128,192,217')              = { 128, 192, 217, 255 }
ParseColorCode('128,192,217,255')          = { 128, 192, 217, 255 }
ParseColorCode('128  ,  192 ,    217,255') = { 128, 192, 217, 255 }
ParseColorCode('80C0D9')                   = { 128, 192, 217, 255 }
ParseColorCode('80C0D9FF')                 = { 128, 192, 217, 255 }