2016-02-04 147 views
1

我有存储在动态切换的文件夹中的xml配置文件。但行为是绝对路径,我需要一个相对路径。 lua代码被编写为与Windows路径(反斜杠)和Mac路径(正斜杠)一起工作。用Lua/C++设置文件路径

在我的mac上,路径可能是/folder/folder/profile1.xml。在正常的应用程序中,程序将返回profile1.xml的文件/位置。它会在同一个文件夹中找到下一个配置文件。 如果我使用相关链接(如../profile2.xml)将应用程序定向到一个新文件夹,程序将找到新的配置文件并将文件/位置作为../profile2.xml返回。然后它不会在同一个文件夹中找到下一个配置文件......它要么寻找下一个配置文件(../),要么在应用程序设置的原始文件夹中查找。我希望它在这个新的文件夹位置中找到下一个请求的配置文件。

现有的代码,设置当前配置文件和配置文件路径是这样的:

local loadedprofile = '' --set by application 
local profilepath = '' --set by application and modified below 

相关的交换功能似乎是:

local function setDirectory(value) 
profilepath = value 
end 

local function setFile(value) 
if loadedprofile ~= value then 
doprofilechange(value) 
end 
end 

local function setFullPath(value) 
local path, profile = value:match("(.-)([^\\/]-%.?([^%.\\/]*))$") 
profilepath = path 
if profile ~= loadedprofile then 
doprofilechange(profile) 
end 

我想我可能需要修改匹配第三个函数的标准来删除../。的

local function setFullPath(value) 
local path, profile = value:match("(.-)([^\\/]-([^%.\\/]*))$") 
profilepath = path 
if profile ~= loadedprofile then 
doprofilechange(profile) 
end 

我真的不知道是怎么写的代码,我只是想调整这个开放源代码(MIDI2LR),以满足我的需求也许是这样的去除可选。在对代码的基本理解中,似乎匹配标准过于复杂。但我想知道我是否正确阅读。我把它解释为:

:match("(.-)([^\\/]-%.?([^%.\\/]*))$") 
(.-) --minimal return 
()$ --from the end of profile path 
[^\\/]- --starts with \ or \\ or /, 0 or more occurrences first result 
%.? --through, with dots optional 
[^%.\\/]* --starts with . or \ or \\ or /, 0 or more occurrences all results 

如果我读它的权利又好像第一次“开始与”完全是多余的,或者说,“从结束”应与第二个有关“打头的。”

我已经注意到setFullPath函数没有所需的结果,这使我认为可能需要添加到setDirectory函数的匹配要求。

任何帮助非常感谢,因为我在我的头上。谢谢!

回答

0

你比赛的解读是不正确,这里是一个更准确的版本:

:match("(.-)([^\\/]-%.?([^%.\\/]*))$") 
(.-) -- Match and grab everything up until the first non slash character 
()$ -- Grab everything up until the end 
[^\\/]- -- Starts with any character OTHER THAN \ or /, 0 or more occurrences first result 
%.? -- single dot optional in the middle of the name (for dot in something.ext) 
[^%.\\/]* -- Any character OTHER THAN . or \ or /, 0 or more occurrences 

的几个注意事项 - %.是文字点。 [^xyz]是逆类,所以除x,y或z以外的每个字符。 \\实际上只是一个反斜杠,这是由于字符串中的转义。

这简单的版本将打破它更易于工作用类似的方式:value:match("(.-)([^\\/]+)$")

您可能需要提供个人资料加载行为的详细信息,它很难告诉你所需要的代码做。你给的例子中路径和配置文件有什么价值?

+0

感谢@Adam B.您的解释更有意义,我使用的lua.org参考(http://www.lua.org/pil/20.2.html),尤其是参考^。我理解了字面点。并且我理解\ escape,但我希望%escape可以在函数字符串中适用。 _这个更简单的版本将以类似的方式打破它,更容易使用:value:match(“(.-)([^ \\ /] +)$”)_ –

+0

我实际上重写它类似'match “(.-)([^ \\ /] *%。?)$”)'但是我可以看到可选的字面点并不是真正必需的,因为它是一个已包含的字符。在两次重写中,文字点都被排除在“以外”语句之外......对于相同的功能,文字点不需要包括在内? –

+0

你的新版本在功能上是等价的,因为'[^ \\ /] *'无论如何都会贪婪地匹配行的其余部分。 %。?在这一点上,只是在最后,并不是必需的,所以它被排除在外。 –