Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed hex values in a lua string literal (i.e. \x equivalent)

In various languages, you can embed hex values in a string literal by using the \x escape sequence:

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

How can I do the same thing in Lua 5.1?

like image 661
Amr Bekhit Avatar asked Apr 30 '15 11:04

Amr Bekhit


People also ask

How do I use string format in Lua?

To use format string we use a simple '%' percentage symbol to represent and print the variable of a different type. To represent different type in Lua we have different symbol available which can be used to print the values of the variable correctly.

How does string sub work Lua?

sub() function takes three arguments in general, the first argument being the name of the string from which we want to extract a piece, the second argument is the i-th index or say, the starting index of the string piece that we want, and the third and the last argument is the j-th index of the last index of the string ...

How do I convert a character to a string in Lua?

The character representation of a decimal or integer value is nothing but the character value, which one can interpret using the ASCII table. In Lua, to convert a decimal value to its internal character value we make use of the string. char() function.

What does char mean in Lua?

char takes the ASCII decimal equivalent of a ASCII character and then converts it into an ASCII character.


1 Answers

Since Lua 3.1, you can use decimal escapes in strings liberals.

Starting with Lua 5.2, you can use hex escapes in string literals.

In Lua 5.1, you can convert hex escapes a posteriori:

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, which do not interpret escape sequences. If you use short strings (in quotes) as in your original code, then \x will be silently converted to x, because Lua 5.1 does not understand \x. Lua 5.2 and later complains about escape sequences that it does not understand.

like image 184
lhf Avatar answered Nov 15 '22 06:11

lhf