【问题标题】:Creating a function in a macro在宏中创建函数
【发布时间】:2016-01-24 11:06:48
【问题描述】:

我正在尝试使用 @:build@:autoBuild 宏向类及其子类的所有实例添加静态变量和静态函数。

我设法让静态变量工作,但我不知道如何从各种 EFunctionEFor 等“构建”函数。

这是我目前的代码:

macro static public function addGetId() :Array<Field>
{
    var fields : Array<Field> = Context.getBuildFields();

    // The static _id field
    var idField = {
        name : "_id",
        doc : null,
        meta : [],
        access : [AStatic, APrivate],
        kind : FVar(macro : Int, macro -1),
        pos : Context.currentPos()
    };

    // The getId function field
    var getIdField = {
        name : "getId",
        doc : "Returns the ID of this command type.",
        meta : [],
        access : [AStatic, APublic],
        kind : FFun({
            params : [],
            args : [],
            expr: // What do I have to write here???
            ret : macro : Int
        }),
        pos : Context.currentPos()
    };

    fields.push(idField);
    fields.push(getIdField);
    return fields;
}

下面是我想要添加的函数在普通代码中的样子,如果它实际上在 .hx 文件中:

public static function getId() : Int
{
    if (_id == -1)
    {
        _id = MySingleton.getInst().myGreatFunction()
    }
    return _id;
};

所以它引用了新添加的_id 变量以及一些单例类函数。
那么:完整的getIdField() 会是什么样子?

额外问题:
我最大的问题是完全缺乏关于这些功能的文档以及手册中的任何有用示例。有没有真正有用的教程来创建这样的函数?

红利问题:
FFun 中的 paramsargs 有什么区别?

【问题讨论】:

    标签: macros haxe


    【解决方案1】:

    您可以像在常规 Haxe 代码中一样使用reification 编写函数体:

    expr: macro {
        if (_id == -1) {
            _id = 0;
        }
        return _id;
    },
    

    params 是类型参数列表,args 是函数接收的参数列表。有一个关于这个on the Haxe Manual的琐事部分:

    琐事:参数与参数

    在其他一些编程语言中,argumentparameter 可以互换使用。在 Haxe 中,argument 用于指代方法,parameter 指代Type Parameters em>。

    【讨论】:

      猜你喜欢
      • 2014-06-15
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      相关资源
      最近更新 更多