basename

function basename( path [, ext] ) --> name

Description

Returns the trailing name of the path, with the ability to remove the extension.

Parameters

path

A unix like path.

ext

If the name component ends with ext this will also be cut off.

Return Values

name

Trailing name of the path.

Code

--ZFUNC-basename-v1
local function basename( path, ext ) --> name
   --ZFUNC-rmsuffix-v1
   local function rmsuffix( str, suffix )
      local suffixlen = string.len( suffix )
      local endsub = string.sub( str, -suffixlen )
      if endsub == suffix then
         local n = string.len( str ) - suffixlen
         return string.sub( str, 1, n )
      else
         return str
      end
   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

   local name = path
   if i ~= 0 then name = string.sub( path, i+1 ) end

   if ext then
      return rmsuffix( name, ext )
   else
      return name
   end
end

return basename

Examples

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

path = "/foo/bar/baz/asdf/quux.html"
t( basename( path ), "quux.html" )
t( basename( path, ".html" ), "quux" )

t( basename( "quux.html" ), "quux.html" )
t( basename( "quux.html", ".html" ), "quux" )

t()