开发者

Error in string.gsub with backslash

开发者 https://www.devze.com 2023-02-10 22:36 出处:网络
local a = \"te\\st\" local b = string.gsub(a,\'\\\',\'\\\\\\\\\') assert(false,b) What am I doing wrong?
local a = "te\st"
local b = string.gsub(a,'\','\\\\')
assert(false,b)

What am I doing wrong?

When开发者_运维百科 I do assert, I want that to the screen the string te\st will be printed... but it's not working

I have a JSON file, that I want to decode it into Lua table. I don't need to print out nothing, I did the assert just to test a local problem.

So what I need is to keep all data in the JSON file that has '\'.


Use [[]] instead of "" or '' if you don't want backslash to have special meaning.

Read about literal strings in the manual.


Have you tried escaping it with the % character instead of \

I don't know if this will help, but I was having a HELL of a time making Lua's gsub match my string with special characters in it that I wanted treated literally... it turned out that instead of using \ as an escape character, or doubling the character, that I needed to prefix the special character with % to make it be treated literally.


Your question wasn't too clear so I'm not 100% sure what you mean. Do you mean that you want the assert to fire when b is equal to the string "te\st"? If so you can do a simple:

assert(b ~= "te\st")

Or I suppse...

assert(b ~= a)


You don't need the gsub. But here it is anyways.

local a = "te\\st"
local b = string.gsub(a,'\\','\\')
assert(false,b)
0

精彩评论

暂无评论...
验证码 换一张
取 消