Skip to content

Instantly share code, notes, and snippets.

@jiaaro

jiaaro/hexcolor.lua

Last active Nov 29, 2020
Embed
What would you like to do?
Hex colors to love2d
-- converts CSS-style hex colors to love2d 0 - 1 scaled colors
-- e.g., hexcolor("ccff99") == {0.8, 1.0, 0.6}
-- supports alpha, e.g., hexcolor("ccff9966") == {0.8, 1.0, 0.6, 0.4}
-- supports shorthand, e.g., hexcolor("cf96") == hexcolor("ccff9966")
-- automatically strips common prefixes, e.g., hexcolor("#cf9"), hexcolor("0xcf9")
local function hexcolor(c)
-- strip leading "#" or "0x" if necessary
if c:sub(1, 1) == "#" then
c = c:sub(2)
elseif c:sub(1,2) == "0x" then
c = c:sub(3)
end
local color = {}
local color_width = (#c < 6) and 1 or 2
local max_val = 16^color_width - 1
for i = 1, #c, color_width do
color[#color+1] = tonumber(c:sub(i, i+color_width-1), 16) / max_val
end
return color
end
return hexcolor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment