WoW:USERAPI HexToRGB: Difference between revisions

From AddOn Studio
Jump to navigation Jump to search
(Damnit, I'll get this right eventually)
 
m (Imp HexToRGB)
Line 2: Line 2:
__NOTOC__
__NOTOC__


Takes a hex string (must be 6 char long!) and converts it to a RGB set (0-255)
Takes a hex string (must be 3 or 6 chars long!) and converts it to a RGB set (0-255). If ''hex'' is invalid, return black (0,0,0).


  local function HexToRGB(hex)
  local function HexToRGB(hex)
local rhex, ghex, bhex = string.sub(hex, 1, 2), string.sub(hex, 3, 4), string.sub(hex, 5, 6)
    local rhex, ghex, bhex
return tonumber(rhex, 16), tonumber(ghex, 16), tonumber(bhex, 16)
    if strlen(hex) == 6 then
        rhex, ghex, bhex = strmatch('([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})', hex)
    elseif strlen(hex) == 3 then
        rhex, ghex, bhex = strmatch('([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])', hex)
        if rhex and ghex and bhex then
            rhex = rhex .. rhex
            ghex = ghex .. ghex
            bhex = bhex .. bhex
        end
    end
    if not (rhex and ghex and bhex) then
        return 0, 0, 0
    else
        return tonumber(rhex, 16), tonumber(ghex, 16), tonumber(bhex, 16)
    end
  end
  end

Revision as of 13:32, 30 September 2007

This page documents a <i>user-defined function</i> that you can copy and paste into your addon. Replace PREFIX with your addon or lib prefix to avoid conflicts between different versions of these functions.

User defined functions


Takes a hex string (must be 3 or 6 chars long!) and converts it to a RGB set (0-255). If hex is invalid, return black (0,0,0).

local function HexToRGB(hex)
    local rhex, ghex, bhex
    if strlen(hex) == 6 then
        rhex, ghex, bhex = strmatch('([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})', hex)
    elseif strlen(hex) == 3 then
        rhex, ghex, bhex = strmatch('([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])', hex)
        if rhex and ghex and bhex then
            rhex = rhex .. rhex
            ghex = ghex .. ghex
            bhex = bhex .. bhex
        end
    end
    if not (rhex and ghex and bhex) then
        return 0, 0, 0
    else
        return tonumber(rhex, 16), tonumber(ghex, 16), tonumber(bhex, 16)
    end
end