Skip to content

Instantly share code, notes, and snippets.

@jaspervdj
Created April 8, 2011 07:36
Show Gist options
  • Save jaspervdj/909436 to your computer and use it in GitHub Desktop.
Save jaspervdj/909436 to your computer and use it in GitHub Desktop.
Invert all hex colors (e.g. #fa74b3) as a unix pipe
#!/usr/bin/lua
-- Pattern matching a hex color, e.g. #fa74b3
local hex_color = '#' .. string.rep('[0-9a-f]', 6)
-- Invert a hex color
function invert_hex_color(color)
-- Drop the initial '#'
color = string.sub(color, 2)
local inverted_color = '#'
-- Fetch the different components and invert them
for i = 0, 2 do
-- Fetch the substring
local component = string.sub(color, 1 + i * 2, 2 + i * 2)
-- Convert to numerical
component = tonumber('0x' .. component)
-- Invert
component = 0xff - component
-- Append
inverted_color = inverted_color .. string.format('%.2x', component)
end
return inverted_color
end
-- Apply on the entire input
for line in io.lines() do
local line = line.gsub(line, hex_color, invert_hex_color)
print(line)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment