How do I delete a folder COMPLETELY?

I am deleting a folder in which I have other files, however, when deleting, the files are simply deleted, not the folder itself. That is, files are deleted, but the folder itself and folders remain in it. Here is my code. Help please.

local function deleteFolder(path)

if not folderExists(path) then

    print("Папка не существует: "..path)

    return false

end

for file in lfs.dir(path) do

    if file ~= "." and file ~= ".." then

        local f = path..'/'..file

        local attr = lfs.attributes(f)

        if attr.mode == "directory" then

            deleteFolder(f)  

        else

            os.remove(f)

        end

    end

end

local success = lfs.rmdir(path)

if success then

    print("Папка успешно удалена: "..path)

    return true

else

    print("Ошибка при удалении папки: "..path)

    return false

end

end

Tested:

local function deleteFolder(path)
  for file in lfs.dir(path) do
    if file ~= "." and file ~= ".." then
      local f = path .. '/' .. file
      local attr, err = lfs.attributes(f)
      if not attr then
        print("Error getting attributes for " .. f .. ": " .. err)
        return false
      end

      if attr.mode == "directory" then
        local success = deleteFolder(f)  -- Recursively delete subdirectories
        if not success then
          return false
        end
      else
        local ok, rmErr = os.remove(f)
        if not ok then
          print("Error deleting file " .. f .. ": " .. rmErr)
          return false
        end
      end
    end
  end

    -- Remove the now-empty directory
    local success, rmdirErr = lfs.rmdir(path)
    if success then
      print("Folder successfully deleted: " .. path)
      return true
    else
      print("Error deleting folder " .. path .. ": " .. rmdirErr)
      return false
    end
end
1 Like

This code doesn’t work for me for some reason. This is where I create a folder: C:\Users\User\AppData\Local\Corona Labs\Corona Simulator\SandboxnameProject\Documents\Projects

Projects is the folder that needs to be deleted. There are other folders in it. However, when calling your function, it writes this in the console: Error deleting folder test: No such file or directory

Here is the code for creating a folder just in case:

function createFolder(folderName, path)

   local fullPath = path.."/"..folderName

   if (lfs.attributes(fullPath) == nil) then

       local success = lfs.mkdir(fullPath)

       if (success) then

           print("Папка успешно создана: "..fullPath)

       else

           print("Ошибка при создании папки: "..fullPath)

       end

   else

       print("Папка уже существует: "..fullPath)

      

   end

end

Can you confirm that the folder does exist via Windows Explorer?

If it does exist, can you provide full code to better assist?

1 Like