使用 Lua 脚本启用 bash 输出颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1718403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Enable bash output color with Lua script
提问by Wookai
I have several Lua scripts that run experiences and output a lot of information, in text files and in the console. I'd like to add some colors in the console output, to make it more readable.
我有几个 Lua 脚本,可以在文本文件和控制台中运行体验并输出大量信息。我想在控制台输出中添加一些颜色,使其更具可读性。
I know that it's possible to color the output of bash scripts using the ANSI escape sequences. For example :
我知道可以使用 ANSI 转义序列为 bash 脚本的输出着色。例如 :
$ echo -e "This is red->\e[00;31mRED\e[00m"
I tried to do the same in Lua :
我试图在 Lua 中做同样的事情:
$ lua -e "io.write('This is red->\e[00;31mRED\e[00m\n')"
but it does not work. I also tried with print()instead of io.write(), but the result is the same.
但它不起作用。我也试过用print()而不是io.write(),但结果是一样的。
回答by jkndrkn
lua -e "print('This is red->\27[31mred\n')"
lua -e "print('This is red->\27[31mred\n')"
Note the \27. Whenever Lua sees a \followed by a decimal number, it converts this decimal number into its ASCII equivalent. I used \27 to obtain the bash \033 ESC character. More info here.
注意\27。每当 Lua 看到 a\后面跟着一个十进制数时,它就会将这个十进制数转换成它的 ASCII 等价物。我使用 \27 来获取 bash \033 ESC 字符。更多信息在这里。
回答by Mark Rushakoff
It can certainly be done in Lua; the trick is just getting the escape sequence right. You can use string.charto write a specific ASCII value out:
在 Lua 中当然可以做到;诀窍是让转义序列正确。您可以使用string.char写出特定的 ASCII 值:
$ echo -e '\E[37;44m'"3[1mHello3[0m" # white on blue
Hello
$ echo -e '\E[37;44m'"3[1mHello3[0m" | xxd # check out hex dump of codes
0000000: 1b5b 3337 3b34 346d 1b5b 316d 4865 6c6c .[37;44m.[1mHell
0000010: 6f1b 5b30 6d0a o.[0m.
$ lua -e "for _,i in ipairs{0x1b,0x5b,0x33,0x37,0x3b,0x34,0x34,0x6d,\
0x1b,0x5b,0x31,0x48,0x65,0x6c,0x6c,0x6f,0x1b,0x5b,0x30,0x6d,0x0a} \
do io.write(string.char(i)) end" # prints out "Hello" in white on blue again
Hello

