Equivalent to lua python repr

Is there an equivalent Python function 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 it is not an escape character in the Lua string. I googled and can't find anything. Lots to find about putting non-printable in a string, nothing about creating a printable version with non-printable characters.

+4
source share
1 answer

The closest equivalent will be the %qoption string.format.

The option qformats the string between double quotes, using escape sequences when necessary, to ensure that the Lua interpreter reads securely. For example, a call

 string.format('%q', 'a string with "quotes" and \n new line')

can output a line:

"a string with \"quotes\" and \
  new line"

You will notice that newlines are not converted to a couple of characters \n. If you prefer this, try the following function:

function repr(str)
    return string.format("%q", str):gsub("\\\n", "\\n")
end
+5
source

Source: https://habr.com/ru/post/1525957/


All Articles