Ansi Terminal Colors

lua-users home
wiki

Someone on IRC asked how to do colors on a console one morning in 2009, so Rob Hoelz decided to whip up a quick module for ANSI terminal color manipulation [1]. The version from 2011 by Enrique García (luarocks install ansicolors), while based on the code below, has different background names and a different user interface (luarocks doc ansicolors).

Here is Rob's original version:

local pairs = pairs
local tostring = tostring
local setmetatable = setmetatable
local schar = string.char

module 'ansicolors'

local colormt = {}

function colormt:__tostring()
    return self.value
end

function colormt:__concat(other)
    return tostring(self) .. tostring(other)
end

function colormt:__call(s)
    return self .. s .. _M.reset
end

colormt.__metatable = {}

local function makecolor(value)
    return setmetatable({ value = schar(27) .. '[' .. tostring(value) .. 'm' }, colormt)
end

local colors = {
    -- attributes
    reset = 0,
    clear = 0,
    bright = 1,
    dim = 2,
    underscore = 4,
    blink = 5,
    reverse = 7,
    hidden = 8,

    -- foreground
    black = 30,
    red = 31,
    green = 32,
    yellow = 33,
    blue = 34,
    magenta = 35,
    cyan = 36,
    white = 37,

    -- background
    onblack = 40,
    onred = 41,
    ongreen = 42,
    onyellow = 43,
    onblue = 44,
    onmagenta = 45,
    oncyan = 46,
    onwhite = 47,
}

for c, v in pairs(colors) do
    _M[c] = makecolor(v)
end

And here's some ways you can use it:

require "ansicolors"

print(ansicolors.red .. 'hello from the Red world!' .. ansicolors.reset)
print(ansicolors.blue .. 'go blue!' .. ansicolors.clear) -- clear is a synonym for reset
print(ansicolors.underscore .. colors.yellow .. colors.onblue .. 'crazy stuff' .. ansicolors.reset)
print(ansicolors.red 'no need to worry about resetting here!') -- functional interface


RecentChanges · preferences
edit · history
Last edited April 29, 2015 6:25 am GMT (diff)