array|译:Gamemaker Studio 2.3 语法详解( 五 )


scr_greet("hi!");// 跟以前一样
other .explode;// 这样可以
init_s [i];// 这样也可以
method (other,scr_some);// 对'other'执行'scr_some' , 不用加'with'内置函数引用
可以这样
varf =show_debug_message;
f ("hello!");
而且我们可以自动为内置函数建立索引 。
varfunctions ={};
for(vari =0;i <10000;i++){
varname =_get_name(i);
if(string_char_at(name,1)=="<")break;
functions [$name]=method(undefined,i);
show_debug_message(string(i)+": "+name);
}
// `functions` now contains name->method pairs
这会输出:
0:camera_create
1:camera_create_view
2:camera_destroy
...
2862:layer_sequence_get_speedscale
2863:layer_sequence_get_length
2864:sequence_instance_exists
索引对于调试和脚本工具来说是非常方便的--例如 , GMLive 现在使用这种机制 , 而不是有一个充满脚本的庞大文件来包装每一个已知的内置函数 。
Constructor(构造函数)
Constructor 是一个标有 Constructors 后缀关键字的函数 。
functionVector2(_x,_y)constructor {
x =_x;
y =_y;
}
这使你能够做到
varv =newVector2(4,5);
show_debug_message (v.x);// 4
show_debug_message (v);// { x: 4, y: 5 }
简而言之 ,new 关键字可以自动创建一个空结构 , 为它调用构造函数 , 然后返回它 。 就像其他编程语言中的类一样! 但还有更多 。
Static variables 静态变量
GMS2 将把 constructor 中的静态变量视为存在于由它创建的 struct 实例中 , 只要 struct 实例没有覆盖该变量 。
这类似于变量定义对对象的作用 , 或原型在其他编程语言中的作用(如 Java 原型或 Lua 的元数据) 。
这可以用于默认值(然后可以覆盖) , 但最重要的是 , 可以向 struct 添加 method, 而不需要在每个 struct 实例中实际存储:
functionVector2(_x,_y)constructor {
x =_x;
y =_y;
staticadd =function(v){
x +=v.x;
y +=v.y;
}
}
// ... 然后
vara =newVector2(1,2);
varb =newVector2(3,4);
a.add(b);
show_debug_message (a);// { x : 4, y : 6 }
注意:如果您想在 constructor 中直接覆盖静态变量(而不是在其中的 function 中) , 您需要使用 self.variable 来区分 static variable 和 new struct 的变量:
functionEntityconstructor {
staticuid =0;
self.uid =uid++;
}
(这将给每个实体一个唯一的 ID )
Inheritance(继承)
一个 constructor 可以使用: Parent 语法从另一个 constructor 继承:
functionElement(_x,_y)constructor {
staticstep =function{};
staticdraw =function(_x,_y){};
x =_x;

推荐阅读