How to embed hex values in a lua string literal (i.e. \x equivalent)
Solution 1
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.
Solution 2
(From the Lua 5.1 reference)
You can embed decimal values in a string literal in Lua by using the \ddd
escape sequence, where ddd
is a sequence of up to three decimal digits. For example:
"\72ell\111"
is the same as "hello"
Amr Bekhit
Embedded System Engineer, owner of HelmPCB, an embedded systems consultancy specialising in ATEX/IECEx design, Embedded Linux, LoRaWAN and low-power IoT.
Updated on June 04, 2022Comments
-
Amr Bekhit almost 2 years
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?
-
Paul Kulchenko almost 9 yearsIf you are using decimal value on strings that mix control and regular characters, I suggest you always use 3 positions (and not up-to-3) or convert all characters, otherwise you are risking turning "\n3" into "\103", which is not the same as "\0103"
-
Amr Bekhit almost 9 yearsAgreed, I was surprised when I saw the "up to three" statement in the documentation and felt it was nothing but trouble!
-
Amr Bekhit almost 9 yearsI like this answer because you explain how to go about doing exactly what I asked, even though the language doesn't support it be default. I think if you can reference the existing ability to embed decimal values in string literals (i.e. combine my answer and yours), then I'll accept this answer.
-
Nas Banov over 7 yearsany idea why this seems to work for me in 5.1?!
print(_VERSION, '\xff') >>> Lua 5.1 \255
-
lhf over 7 years@NasBanov, perhaps you're running LuaJIT instead of Lua from lua.org.
-
Nas Banov over 7 years@lhf you got it! I was trying in ZeroBrane Studio console and when not debugging it is indeed LuaJIT (has
jit
table). When i debug at a breakpoint though, no more JIT and the output is"Lua 5.1" "xff"
- perfect match!