joinpath

function joinpath( tab ) --> path

Description

Joins any number of path elements into a single path, adding a separating slash if necessary. The result is Cleaned; in particular, all empty strings are ignored.

Parameters

tab

Array table with the path components.

Return Values

path

Valid path string.

Code

--ZFUNC-joinpath-v1
local function joinpath( tab ) --> path
   --ZFUNC-firstchar-v1
   local function firstchar( str )
      return string.sub( str, 1, 1 )
   end

   --ZFUNC-lastchar-v1
   local function lastchar( str )
      return string.sub( str, #str )
   end

   local rooted = false
   local tmptab = {}
   for k, s in ipairs( tab ) do
      if k == 1 and firstchar( s ) == "/" then
         rooted = true
      end

      if firstchar( s ) == "/" then
         s = s:sub( 2 )
      end
      if lastchar( s ) == "/" then
         s = s:sub( 1, #s - 1 )
      end

      if #s > 0 then
         table.insert( tmptab, s )
      end
   end

   if rooted then
      return "/"..table.concat( tmptab, "/" )
   end

   return table.concat( tmptab, "/" )
end

return joinpath

Examples

local t = require( "taptest" )
local joinpath = require( "joinpath" )

t( joinpath{ "abc", "def", "ghi" }, "abc/def/ghi" )
t( joinpath{ "abc/", "def", "/ghi" }, "abc/def/ghi" )
t( joinpath{ "abc", "/def/", "ghi" }, "abc/def/ghi" )
t( joinpath{ "abc", "def/ghi" }, "abc/def/ghi" )

t( joinpath{}, "" )

t( joinpath{ "/a", "/b/c/" }, "/a/b/c" )

t( joinpath{ "/", "/", "/" }, "/" )

t()

See also