mkpath

function mkpath( path ) --> res, err

Description

This creates a directory and any missing ancestor directories that are defined in the path.

Parameters

path

The path with the directories that should be created.

Return Values

res

true or nil if an error occurse.

err

A message if an error occurse otherwise nil.

Code

local lfs = require( "lfs" ) --ZREQ-lfs
--ZFUNC-mkpath-v1
local function mkpath( path ) --> res, err
   --ZFUNC-separator-v1
   local function separator()
      return _G.package.config:sub( 1, 1 )
   end

   --ZFUNC-splitpath-v1
   local function splitpath( path )
      local tab = {}
      for token in string.gmatch( path, "[^/]+" ) do
         if #token > 0 then
            table.insert( tab, token )
         end
      end
      return tab
   end

   local p = "."
   local res, err
   for i, name in ipairs( splitpath( path ) ) do
      p = p.."/"..name
      res, err = lfs.mkdir( p )

      if err then return res, err end
   end

   return true
end

return mkpath

Examples

local t = require( "taptest" )
local mkpath = require( "mkpath" )
local isdir = require( "isdir" )

t( isdir( "a" ), false )

res, err = mkpath( "a/b/c" )
t( res, true )

t( isdir( "a" ), true )
t( isdir( "a/b" ), true )
t( isdir( "a/b/c" ), true )

os.remove( "a/b/c" )
os.remove( "a/b" )
os.remove( "a" )

t()

See also