Last active
June 1, 2026 20:17
-
-
Save saantonandre/f641a6e1e9215543b31b4fafa733397c to your computer and use it in GitHub Desktop.
Lua HEX to RGB, short hex and alpha channel support, validation, fractional/integer output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| local utils = {} | |
| --- Converts a hex color string to rgb/rgba values | |
| --- @param hexColor string | |
| --- @param asFraction? boolean | |
| function utils.hexToRgb(hexColor, asFraction) | |
| if (not utils.isValidHexColor(hexColor)) then error("Invalid hex color string: " .. hexColor) end | |
| local parse = function(f, t) | |
| local value = tonumber("0x" .. hexColor:sub(f, t or f)) * (t and 1 or 17) | |
| return (asFraction and value / 255) or value | |
| end | |
| if (#hexColor == 4) then return parse(2), parse(3), parse(4); end | |
| if (#hexColor == 5) then return parse(2), parse(3), parse(4), parse(5); end | |
| if (#hexColor == 7) then return parse(2, 3), parse(4, 5), parse(6, 7); end | |
| return parse(2, 3), parse(4, 5), parse(6, 7), parse(8, 9); | |
| end | |
| ---Returns whether or not `hexColor` is a valid hex color | |
| ---@param hexColor string | |
| ---@returns boolean | |
| function utils.isValidHexColor(hexColor) | |
| local invalidFormat = hexColor:find("^#%x%x%x+$") == nil | |
| if (invalidFormat) then return false end | |
| local invalidLength = true | |
| for _, value in ipairs({ 4, 5, 7, 9 }) do | |
| if (value == #hexColor) then | |
| invalidLength = false; break; | |
| end | |
| end | |
| return not invalidLength | |
| end | |
| -- examples: | |
| print(utils.hexToRgb("#10fa")) -- 17 0 255 170 | |
| print(utils.hexToRgb("#ac1")) -- 170 204 17 | |
| print(utils.hexToRgb("#fff6")) -- 255 255 255 102 | |
| print(utils.hexToRgb("#ba8144", true)) -- 0.72941176470588 0.50588235294118 0.26666666666667 | |
| print(utils.hexToRgb("#fff12355")) -- 255 241 35 85 | |
| print(utils.hexToRgb("#oh no")) -- (error) **Invalid hex color string: #oh no** | |
| return utils |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment