Skip to content

Instantly share code, notes, and snippets.

@jiaaro
Last active January 13, 2024 09:35
Show Gist options
  • Save jiaaro/da1f16cab12e957eda79377376faa2f7 to your computer and use it in GitHub Desktop.
Save jiaaro/da1f16cab12e957eda79377376faa2f7 to your computer and use it in GitHub Desktop.
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