Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace \n string with real \n in lua

Tags:

lua

Is there a way in lua when a string containing \n or \t given, that we are able to get the real meaning of \n(real new line) or \t(tab) to a string that would get pass on. This has to be done before printing as it would solve the problem! But I don't want to print the updated string!

I used gsub but don't know how to represent a actual new line. (A tab can be represented by some number of white-spaces)

like image 333
Charith_32 Avatar asked Aug 01 '26 23:08

Charith_32


1 Answers

Refer to Lua 5.3 Lua Reference Manual 6.4 String Manipulation string.gsub:

string.gsub (s, pattern, repl [, n])

Returns a copy of s in which all (or the first n, if given) occurrences of the pattern (see §6.4.1) have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred. The name gsub comes from Global SUBstitution.

If repl is a table, then the table is queried for every match, using the first capture as the key.

local myString = "hello\\n\\tworld"
print(myString)

hello\n\tworld

print((myString:gsub("\\([nt])", {n="\n", t="\t"})))
hello
  world!!!
like image 110
Piglet Avatar answered Aug 04 '26 12:08

Piglet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!