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
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.
It can certainly be done in Lua; the trick is just getting the escape sequence right. You can use string.char
to write a specific ASCII value out:
$ echo -e '\E[37;44m'"\033[1mHello\033[0m" # white on blue Hello $ echo -e '\E[37;44m'"\033[1mHello\033[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