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( "taptest" )
local cutpath = require( "cutpath" )

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

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

t()

Inspired by

See also