1
votes
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 '\'.

4
I assume that if i solve that small example, i will be able to use the same solution for the JSON part - Yoni
Please specify what is in b and what do you expect/want the result to be to get better answers - sbk
Mind explaining your problem a little better / with more code inlcuding the json part? - luastoned

4 Answers

3
votes

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

Read about literal strings in the manual.

2
votes

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.

0
votes

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)
0
votes

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

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