Error in manipulating sting with "\" in Lua

Viewed 71
local filepath = "c:\\temp\\parentdir"
local dirname = string.match(filepath, "[^\\]+$")
print(dirname)

Above code is giving correct output: parentdir

Then if I use same code but only single "\" as below

local filepath = "c:\temp\parentdir"
local dirname = string.match(filepath, "[^\\]+$")
print(dirname)

I'm getting this error

"lua: main.lua:1: invalid escape sequence near '"c: emp\p'"

please help. How we can solve this issue programatically

1 Answers

It isn't a issue, becaouse you not provide c:\temp\parentdir literally, but c:{tab}emp{unknown_character}arentdir. To provide c:\temp\parentdir you can use:

  1. "c:\\temp\\parentdir"
  2. 'c:\\temp\\parentdir'
  3. [[c:\temp\parentdir]]

If you read c:\temp\parentdir from file or input you not have to add second \, because this is only in code escape character. More about here.

Second solution is to use / instead \.

Related