Godot:目录递归函数stackoverflow

问题描述

以下函数打印路径中的目录和文件,我希望它使用递归函数进入目录和子目录。这会导致计算器溢出错误。它仅在不调用“RecursiveSearch”函数但仅打印目录和文件而不是子目录时才有效。

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)

解决方法

Directory.list_dir_begin() 仅列出目录的直接子级。要递归进入子目录,您需要为该子目录创建一个新的 Directory 对象,并在其上调用您的 RecursiveSearch。

就目前而言,您的函数使用自己的参数调用自身。它会做同样的事情——用相同的参数调用自己——一次又一次,直到达到递归限制。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...