Module:Color

local p = {} local colorCodes = mw.loadData( 'Module:Color/codes' ) local colorIds = mw.loadData( 'Module:Color/ids' )

local function findColorName(colorId) for name, id in pairs(colorIds) do		if id == colorId then return name end end return '' end

function p.colors( f ) local args = f:getParent.args local colorBlocks = {} local size = 20 local colorNameLower = '' local colorId = 0 local colorCode = '' local unknownId = 256

--This slices one parameter into a variable number of parameters with a comma as a delimiter. --This allows the list to be called into another Template as its own parameter. local M_SLICES = {} for part in string.gmatch((args[1])..',', "([^,]*),") do 	local slice = part:match "^%s*(.-)%s*$" if #slice <= 3 and tonumber(slice) ~= nil then slice = findColorName(slice) end table.insert(M_SLICES, slice) end

local colorIdsOrdered={} for _, colorNameInput in ipairs(M_SLICES) do   colorNameLower = colorNameInput:gsub('%W',''):lower

colorId = colorIds[colorNameLower] if colorId ~= nil then colorId = tonumber(colorId) end

-- colorId must be a number for the sorting later -- internally in this module, an unknown id is represented by numbers > 256 if colorId == nil then colorId = unknownId unknownId = unknownId + 1 end

colorCode = colorCodes[colorNameLower]

if colorCode ~= nil and not p.isColorNameInTable(colorIdsOrdered, colorNameLower) then table.insert(colorIdsOrdered, {colorId, colorCode, colorNameInput}) end end

-- the sorting function must be stable, i.e. a==b => b==a table.sort(colorIdsOrdered, function(a,b) return a[1] < b[1] end)

-- colorInfo[1]: color Id -- colorInfo[2]: color code (hex) -- colorInfo[3]: color name as entered in the template call for _, colorInfo in ipairs(colorIdsOrdered) do   table.insert(colorBlocks,''..(colorInfo[1] < 256 and ' '..colorInfo[1]..' ' or '')..' ') end return ' '..table.concat(colorBlocks)..' ' end

function p.isColorNameInTable(tab, colorNameLower) for _, colorInfo in ipairs(tab) do   if colorInfo[3] == colorNameLower then return true end end return false end

return p