【问题标题】:Creating a closure in ext在 ext 中创建闭包
【发布时间】:2016-10-27 22:44:42
【问题描述】:

我正在执行LibGDX's TexturePacker with gradle 中给出的texturePacker 任务。

project.ext {
    // ...
    texturePacker = ["assets", "../android/assets", "texture"]
}

import com.badlogic.gdx.tools.texturepacker.TexturePacker
task texturePacker << {
    if (project.ext.has('texturePacker')) {
        logger.info "Calling TexturePacker: "+ texturePacker
        TexturePacker.process(texturePacker[0], texturePacker[1], texturePacker[2])
    }
}

我得到了它对类路径的建议修改和添加的扩展变量。现在我想将textPacker 扩展变量修改为具有描述性成员名称而不是数组的闭包(这是正确的术语吗?)。我试过这样做:

project.ext {
    // ...
    texturePacker {
        inputDir = "assets"
        outputDir = "../android/assets"
        packFileName = "texture"
    }
}

这会产生以下错误:

错误:在 org.gradle.api.Project 类型的项目 ':desktop' 上找不到参数 [build_4dusyb6n0t7j9dfuws8cc2jlu$_run_closure1$_closure7@6305684e] 的方法 texturePacker()。

我对 gradle 和 groovy 很陌生,所以我不知道这个错误是什么意思。更重要的是,做我想做的事情的正确方法是什么?

【问题讨论】:

    标签: gradle groovy libgdx


    【解决方案1】:

    我想,闭包不是你需要的东西,因为它不是用来存储变量,而是用来存储一些可执行代码。顺便说一句,如果需要存储,你必须添加=,如下:

    project.ext {
        texturePacker = {
            inputDir = "assets"
            outputDir = "../android/assets"
            packFileName = "texture"
        }
    }
    

    无论如何,如果需要在texturePacker 变量中存储变量,您宁愿使用 Map 类型,然后使用 Closure。可以这样做:

    project.ext {
        texturePacker = [
            inputDir : "assets",
            outputDir : "../android/assets",
            packFileName : "texture"
        ]
    }
    

    然后你可以通过名字来访问这个变量,如下:

    println texturePacker.inputDir
    

    【讨论】:

      【解决方案2】:

      或者,我认为您也可以使用这些属性来实现您自己的任务。您可以使用DefaultTask,这是常规任务的标准实现(我相信这对您来说已经足够了);

      class TexturePacker extends DefaultTask {
           String inputDir; // a property - not a field!
           String outputDir; // a property - not a field!
           ...
      
           @TaskAction
           void doSth(){
              // do sth with properties above - that will be called automatically by gradle as a task-execution
           }
      }
      
      task packer (type:TexturePacker) {
           inputDir '<your-input-dir>'
           outputDir '<your-output-dir>'
      }
      

      语法可能不太正确,但我想你明白了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-06
        相关资源
        最近更新 更多