Is there an equivalent function to Python's repr() function in Lua? In other words a function that prints non-printable characters with \x where x is n or b etc, or \000 code if not a Lua string escape character. I've googled and can't find anything. Lots to find about putting non-printables in a string, nothing about generating a print-friendly version of a string with non-printable chars.
The closest equivalent would be the %q
option for string.format
.
The
q
option formats a string between double quotes, using escape sequences when necessary to ensure that it can safely be read back by the Lua interpreter. For instance, the callstring.format('%q', 'a string with "quotes" and \n new line')
may produce the string:
"a string with \"quotes\" and \ new line"
You'll notice that new lines are not converted into the the character pair \n
. If you would prefer that, try the following function:
function repr(str)
return string.format("%q", str):gsub("\\\n", "\\n")
end