2016-02-04 55 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

你的新版本在功能上是等價的,因爲'[^ \\ /] *'無論如何都會貪婪地匹配行的其餘部分。 %。?在這一點上,只是在最後,並不是必需的,所以它被排除在外。 –