ANSI 終端機色彩

lua-users home
wiki

2009 年的某天早上,有人在 IRC 上詢問如何為控制台套用色彩,因此 Rob Hoelz 決定迅速建立一個用於 ANSI 終端機色彩操作的模組 [1]。Enrique Garc�a 於 2011 年發布的版本(luarocks 安裝 ansicolors)雖然是基於以下程式碼,但背景名稱和使用者介面不同(luarocks doc ansicolors)。

以下為 Rob 的原始版本

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

以下為一些使用方式

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


近期變更 · 喜好設定
編輯 · 歷史記錄
最後編輯時間 2015 年 4 月 29 日 上午 6:25 (格林威治標準時間) (diff)