lua相当于python repr

Oli*_*ver 4 python lua repr

在Lua中是否有与Python的repr()函数相同的函数?换句话说,一个函数使用\ x打印不可打印的字符,其中x是n或b等,如果不是Lua字符串转义字符,则打印\ 000代码.我用谷歌搜索,找不到任何东西.很多关于将非printables放在字符串中的信息,没有关于使用不可打印的字符生成字符串的打印友好版本.

Tim*_*per 5

最接近的等价物是.的%q选项string.format.

q选项在双引号之间格式化一个字符串,必要时使用转义序列以确保Lua解释器可以安全地回读它.例如,电话

 string.format('%q', 'a string with "quotes" and \n new line')
Run Code Online (Sandbox Code Playgroud)

可能会产生字符串:

"a string with \"quotes\" and \
  new line"
Run Code Online (Sandbox Code Playgroud)

您会注意到新行未转换为字符对\n.如果您愿意,请尝试以下功能:

function repr(str)
    return string.format("%q", str):gsub("\\\n", "\\n")
end
Run Code Online (Sandbox Code Playgroud)