0

The following function prints the directories and files within a path, I want it to go into the directories and sub directories by using a recursive function. This causes a stackoverflow error. It only works if doesn't call "RecursiveSearch" func but only prints out directories and files but not subdirectories.

extends Node


func RecursiveSearch(dir):
    var path = ("res://")
    var err = dir.open(path)
    if err != OK:
        print("error occurred")
        return
        
    dir.list_dir_begin() # points to the first one, true ignores special directory entries (.) and (..)
    
    var name = dir.get_next() # retrieves the firdt file or dir
    
    while name != "": 
        if dir.current_is_dir(): # test if it's a dir type
            print("dir : " , name)
            RecursiveSearch(dir)
        elif !dir.current_is_dir():
            print("file : " , name)
        else:
            break
            
        name = dir.get_next() # points to the next dir or file

    dir.list_dir_end()
    
    
func _ready():
    var dir = Directory.new()
    RecursiveSearch(dir)
Alonso
  • 25
  • 3

1 Answers1

0

Directory.list_dir_begin() only lists the immediate children of a directory. To recurse into a subdirectory, you will need to create a new Directory object for the subdirectory, and call your RecursiveSearch on that.

As it stands, your function calls itself with its own argument. It will do the exact same thing--call itself with the same argument--again and again until it hits the recursion limit.

James Westman
  • 2,680
  • 1
  • 15
  • 20