How to embed hexadecimal values ​​in lua string literal (i.e. \ X equivalent)

In different languages, you can insert hexadecimal values ​​into a string literal using the escape sequence \ x:

"hello \x77\x6f\x72\x6c\x64"

How can I do the same in Lua 5.1?

+5
source share
2 answers

Since Lua 3.1, you can use decimal escape sequences in liberal strings.

Starting with Lua 5.2, you can use hexadecimal escape sequences in string literals.

In Lua 5.1, you can convert hex escape posteriori files:

 s=[[hello \x77\x6f\x72\x6c\x64]] s=s:gsub("\\x(%x%x)",function (x) return string.char(tonumber(x,16)) end) print(s) 

Note the use of long strings that do not interpret escape sequences. If you use short strings (in quotation marks), as in your source code, then \x will silently convert to x , because Lua 5.1 does not understand \x . Lua 5.2 and later complain about escape sequences that it does not understand.

+8
source

(From link Lua 5.1 )

You can embed decimal values ​​in a string literal in Lua using the \ddd escape sequence, where ddd is a sequence of three decimal digits. For instance:

"\72ell\111" matches "hello"

+3
source

All Articles