我有两个绝对文件路径(A
和B
)。我想在A
的相对路径中转换B
。我怎么能用Lua脚本来做呢?
答案 0 :(得分:3)
执行此操作的算法是:
A="/a/b/c/d.txt" B="/a/b/e/f.txt"
转到A="c/d.txt" B="e/f.txt"
)A={"c", "d.txt"} B={"e", "f.txt"}
B
指向常规文件,请删除B
的最后一个元素。如果它指向一个目录,请保持原样。 (对于我们的示例,您将获得B={"e"}
)..
的开头插入A
。 (由A={"..", "c", "d.txt"}
生成)A
的内容以获取最终结果:"../c/d.txt"
这是一个非常粗略的实现,无需库。它不处理任何边缘情况,如from
和to
相同,或者一个是另一个的前缀。 (我的意思是在这些情况下函数肯定会破坏,因为mismatch
将等于0
。)这主要是因为我很懒惰;还因为代码已经变得有点长,这会损害可读性。
-- to and from have to be in a canonical absolute form at
-- this point
to = "/a/b/c/d.txt"
from = "/a/b/e/f.txt"
min_len = math.min(to:len(), from:len())
mismatch = 0
print(min_len)
for i = 1, min_len do
if to:sub(i, i) ~= from:sub(i, i) then
mismatch = i
break
end
end
-- handle edge cases here
-- the parts of `a` and `b` that differ
to_diff = to:sub(mismatch)
from_diff = from:sub(mismatch)
from_file = io.open(from)
from_is_dir = false
if (from_file) then
-- check if `from` is a directory
result, err_msg, err_no = from_file:read(0)
if (err_no == 21) then -- EISDIR - `from` is a directory
end
result = ""
for slash in from_diff:gmatch("/") do
result = result .. "../"
end
if from_is_dir then
result = result .. "../"
end
result = result .. to_diff
print(result) --> ../c/d.txt
答案 1 :(得分:2)