跳到主要内容
版本:release

变量

语法

  • 标识符

描述

变量是一个用标识符指代的值,一些地方也将其称为 具名值,表示:变量这一概念让值有了名字。

变量包含常量和非常量,非常量的变量可以被作为 赋值表达式 的左值进行赋值操作。

按照行为特性分类,变量可以被分为:

对象成员变量

关于对象的成员变量和成员常量的信息,参见 字段

// a.gs
int member = 15;
parallel int parallel_member := 20;

const string EXAMPLE = "example"; // 成员常量

void foo()
{
// EXAMPLE = "test"; // Error: 不能为成员常量赋值

member = 30; // Ok: 成员变量可以被赋值
parallel_member := 40; // Ok: parallel 成员变量可以被赋值,使用 `:=` 操作符

writeln(EXAMPLE); // 输出 "example"
writeln(member); // 输出 30
writeln(parallel_member); // 输出 40
}

局部变量

局部变量是定义在函数内的局部作用域的变量,这些变量只能在其定义的作用域内访问。

void foo()
{
int local_var = 10; // 定义局部变量

writeln(local_var); // 输出 10

local_var = 20; // 修改局部变量的值
writeln(local_var); // 输出 20
}

其他常量

作为语法糖,当通过 importcomponent 引入一个脚本作为导入脚本或组件之后,文件的纯文件名本身可以被作为一个常量;常量的值为导入脚本或组件的路径:

import "/example/value.gs" as alias_value;
import pkg.demo;
component pkg.demo_component;

writeln(value); // 输出 "/example/value.gs"
writeln(alias_value); // 输出 "/example/value.gs"
writeln(demo); // 输出 "pkg.demo"
writeln(demo_component); // 输出 "pkg.demo_component"

如果定义了枚举,枚举的类型名也是一个常量,其值是一个 map,里面记录着枚举成员名到其值的映射;同时还包含反向的映射:

enum Color {
Red = 1,
Green = 2,
Blue = 3
}
writeln(Color);

上述程序将输出:

{ /* sizeof() == 5 */
"__reverse_enum_map__" : { /* sizeof() == 3 */
1 : "Red",
2 : "Green",
3 : "Blue",
},
"__memo__" : { },
"Red" : Color.Red(1) @ /test.gs,
"Green" : Color.Green(2) @ /test.gs,
"Blue" : Color.Blue(3) @ /test.gs,
}

如果定义了 class,则类名也是一个常量,其值是是包含了类的成员和方法的 map。这个 map 被 称为 parent class

class Example {
int member = 10;

static void static_method() {
writeln("Hello from static method");
}
void method(Example self) {
writeln("Hello from method");
}
}
writeln(Example); // 输出类的 parent class

上述程序将输出:

{ /* sizeof() == 6 */
"member" : 10,
"static_method" : (: .static_method@Example :)<no this>,
"method" : (: .method@Example :)<no this>,
"__class__" : "Example",
"__program__" : "/test.gs",
"__inherits__" : [ ],
}