lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

2013/11/29 Paul Merrell <>:
> To avoid reinventing the wheel, I thought I'd ask whether anyone has a
> function that will return a relative path from absolute paths for the
> current and destination directories? Something along the lines of:
> function(curdir, destdir)
>   ...
>   return reldir
> end
> I googled around but found only a function that has dependencies.[1]

I wrote a path module that might help you implement your function:

In case you're wondering (and didn't click the link) you can install
it with LuaRocks.

As for your specific function, it could look something like that:

local path = require 'path'

function relative(from, to)
    if path.type(from)~='path' then from = path.split(from) end
    if path.type(to)~='path' then to = path.split(to) end
    -- determine where paths diverge
    local i = 0
    while from:sub(0, i) == to:sub(0, i) do
        i = i + 1
    -- roots may be different
    if i == 0 then return nil end
    from = from:sub(i)
    to = to:sub(i)
    -- invert from
    local morf = path.empty
    for i=1,#from do
        morf = morf / '..'
    return morf / to

assert(relative([[C:\Program Files (x86)\MyApp\bin]],
[[C:\Windows\system32]]) == path.split('../../../Windows/system32'))

Note that I just fixed a small bug in the == operator, which could
give false negatives for relative paths. If that's a problem for you
use the Mercurial tip instead of the rock.