Lua Color Converter

I wrote simple lua-script that allows you to use hex and rgb colors (#ffaaff or 198, 0, 198 etc.). It works with Corona SDK too.
Here it is:
I’ll be glad if it helps you.


Super useful, great work! :smiley:

Nice! Thank you for sharing!

1 Like

This does not work.
You should return alpha as fourth component. Something like this:

function to_color(hex, alpha)
	local r, g, b = hex:match("(%w%w)(%w%w)(%w%w)")
	r = (tonumber(r, 16) or 0) / 255
	g = (tonumber(g, 16) or 0) / 255
	b = (tonumber(b, 16) or 0) / 255
	return r, g, b, alpha or 1

Ah, yes, @dmitriy is correct. The example in the readme will not behave properly:

go.set("#label", "color", vmath.vector4(color.rgb(255, 16, 174), 1)

The reason is that with multiple return values only the first value will be used if there are more arguments, in this case the 1 for alpha. It will result in “bad argument #3 to ‘vector4’ (number expected, got no value)”


@dmitriy, @britzl thanks.
Added alpha channel, now everything works fine :slight_smile:



Thank you for this useful script, but it looks like the conversion from hex doesn’t work, or at least I didn’t manage to make it work:

local converted_color = vmath.vector4(color.hex("#ff00ff", 0.5))
go.set("#sprite", "tint", converted_color)

An error message is generated:

It works as intended with the conversion from RGB/RGBA.

Am I missing something? :thinking:

Seems to be an error in the library code on L4 it captures 4 groups but only unpacks 3. Changing the line to local redColor,greenColor,blueColor=hex:match('#?(..)(..)(..)') would work better. There is also this color module that I made, but it might be a bit excesive for your user case however.

1 Like

I forgot to answer, but thanks, you were right :wink: