cutpath

function cutpath( path ) --> dirname, basename

Description

Splits path into a directory(dirname) and file name(basename) component. If there is no Separator in path, returns the function an empty dir and file set to path.

Parameters

path

Unix like string path that should be cut into pieces.

Return Values

dirname

Directory sub path in the full path.

basename

File name component of the path.

Code

--ZFUNC-cutpath-v1
local function cutpath( path ) --> dirname, basename
   --ZFUNC-cutstr-v1
   local function cutstr( str, n )
      return str:sub( 1, n ), str:sub( n + 1, #str )
   end

   local i = #path
   local c = string.sub( path, i, i )
   while i > 0 and c ~= "/" do
      i = i - 1
      c = string.sub( path, i, i )
   end

   if i == 0 then return "", path end

   return cutstr( path, i )
end

return cutpath

Examples

local t = require( "tapered" )
local cutpath = require( "cutpath" )

dirname, basename = cutpath( "quux.html" )
t.is( "", dirname )
t.is( "quux.html", basename )

dirname, basename = cutpath( "/foo/bar/quux.html" )
t.is( "/foo/bar/", dirname )
t.is( "quux.html", basename )

t.done()

Inspired by

See also