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?
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.
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 ...
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.
char takes the ASCII decimal equivalent of a ASCII character and then converts it into an ASCII character.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With