JSDoc 脚本注释

如果希望自定义函数具有代码完成功能并在代码编辑器中以特定方式显示所需的参数,则需要添加一些 JSDoc 样式 注释。这些注释用于告诉自动完成功能应如何在 脚本编辑器 中使用和填写该函数。

提示 您可以使用 语法检查快速修复 菜单 (按 /+ Q 或单击 图标) 自动生成这些注释。当文本光标放在函数标题(即定义函数名称的行)上时,该选项可见。

典型函数标题的格式为:函数名称、函数说明,然后是函数所采用的不同参数 (参数) 的列表,确保每行都以 "///" 三进制斜杠开头,这表示 GameMaker 将注释解析为 JSDoc 样式。您也可以用 /**...*/ 封装 JSDoc 注释,/** 位于自己的行上。

需要为注释本身指定一个标识符 (前面带有 "@") 和内容。可用标识符如下:

标识符内容语法
@function / @funcThe full function name including arguments@func my_func(args)
@description / @descA general description of what the function does@desc <Description goes>
@param / @parameter / @arg / @argumentInformation on an argument, with an optional type in {} (or multiple acceptable types separated by , or |)@param {type,type} name <Parameter description>
@return / @returnsType of data the function returns@return {type,type} <Return description>
语法检查专用
@pureMarks the function as pure@pure
@ignoreHides the function from Feather's autocomplete@ignore
@deprecatedMarks the function as deprecated@deprecated
@context / @selfSets the context for the function, which Feather auto-complete uses to provide contextual information. Can be an object or a constructor.@self <object>

如果您尚未为参数或返回值指定类型,并且正在使用语法检查,则它将根据您的函数体自动为这些参数指定数据类型。

有关 @param@return 的数据类型的信息,请参阅 语法检查数据类型

示例

要了解在编写自己的函数时如何工作,让我们以下列基本示例为例:

function is_same_object(_id, _obj)
{
    if (_id.object_index == _obj)
    {
        return true;
    }
    else return false;
}

此脚本执行的所有操作都是检查某个实例是否与给定对象具有相同的 object_index,并且可以简单地称为:

if (is_same_object(id, obj_Player))
{
    instance_destroy()
}

但是,将其写入代码编辑器将直接显示参数变量名称 (_id_obj),在大多数情况下,这些名称的描述性不强。您可以使用 JSDoc 定义自定义参数名称和说明,以及函数的信息:

/// @function                is_same_object(inst_id, object_id)
/// @description             Check if the given instance belongs to the given object.
/// @param {Id.Instance}     inst_id    The unique instance ID value of the instance to check.
/// @param {Asset.GMObject}  object_id  The object index to be checked against.
/// @return {Bool}

function is_same_object(_inst_id, _object_id)
{
    return _inst_id.object_index == _object_id;
}

现在,在项目中的任何位置调用此函数时,都会看到在 JSDoc 注释中输入的新参数名称:

JSDoc Example 在上图中,顶部显示了自动完成中的功能,底部显示了底部参数帮助器的工作原理。请注意,@param 的可选 " 类型 " 和必填 " 说明 " 部分默认不会显示在 IDE 代码完成中,要查看它们,必须激活 GML 首选项 中的选项。

使用语法检查时,将鼠标悬停在该函数上方时,将会看到有关该函数的详细信息:

您可以用[]括号括起参数名称,以表明它是可选的。然后,代码编辑器将期望在最小必需参数和参数总数之间有任意数量的参数。

例如,请参见以下函数:

/// @function    animate_position(end_x, end_y, start_x, start_y)
/// @desc        Animates the instance to ending point, from optional starting point
/// @arg end_x
/// @arg end_y
/// @arg [start_x]
/// @arg [start_y]

function animate_position (x1, y1, x2, y2)
{
    // Function code
}

start_xstart_y 参数被标记为可选,这意味着代码编辑器现在需要 2 到 4 个参数,如警告消息中所示:

注意 如果在函数声明中使用可选参数,将获得相同的行为。有关详细信息,请参阅脚本函数

由于脚本中可以包含多个函数,因此可以在脚本声明之前为每个脚本添加 JSDoc 注释:

Multiple Functions With JSDoc Comments Example