【Godot】递归扫描文件/目录

Godot 4.0 alpha 16

使用 lambda 表达式递归扫描文件

##  扫描文件
func scan_file(scan_path: String) -> Array[String]:
    var scan_file : Callable = func(path: String, list: Array, callback: Callable):
        var directory := Directory.new()
        var err := directory.open(path)
        if err != OK:
            printerr(err, "\t", path)
            return
        directory.list_dir_begin()
        # 遍历文件
        var dir_list := []
        var file_list := []
        var file := ""
        file = directory.get_next()
        while file != "":
            # 目录
            if directory.current_is_dir() and not file.begins_with("."):
                dir_list.append( path.path_join(file) )
            # 文件
            elif not directory.current_is_dir() and not file.begins_with("."):
                file_list.append( path.path_join(file) )

            file = directory.get_next()
        # 添加
#      list.append_array(dir_list)
        list.append_array(file_list)
        # 递归扫描
        for dir in dir_list:
            callback.call(dir, list, callback)

    var list := []
    scan_file.call( scan_path, list, scan_file )
    print(list)
    return list

发表评论