godot游戏引擎自学入门笔记--GDScript语言细节,官方文档翻译(八)

标识符

Any string that restricts itself to alphabetic characters (a to z and A to Z), digits (0 to 9) and _ qualifies as an identifier. Additionally, identifiers must not begin with a digit. Identifiers are case-sensitive (foo is different from FOO).

字母字符( a 到 z 和 A 到 Z )、数字( 0 到 9 )和 _ 的字符串都可以作为标识符。此外,标识符不能以数字开头。标识符区分大小写( foo 和 FOO 是不同的)。

关键字

The following is the list of keywords supported by the language. Since keywords are reserved words (tokens), they can’t be used as identifiers. Operators (like in, not, and or or) and names of built-in types as listed in the following sections are also reserved.
Keywords are defined in the GDScript tokenizer in case you want to take a look under the hood.

下面是该语言支持的关键字列表。由于关键字是保留字(令牌),它们不能用作标识符。操作符(如 in , not , and 或 or )以及下面列出的内置类型的名称也是保留的。

关键字定义在 GDScript tokenizer 中,假如您想了解其中的内幕

关键字 描述
if 见 if/else/elif.
elif 见 if/else/elif.
else 见 if/else/elif.
for 见 for.
while 见 while.
match 见 match.
break 退出当前 for 或 while 循环的执行。
continue 立即跳到 for 或 while 循环的下一个迭代。
pass 在语法上要求语句但不希望执行代码的地方使用,例如在空函数中。
return 从函数返回一个值。
class 定义一个类。
extends 定义用当前类扩展什么类。
is 测试变量是扩展给定的类,还是具有给定的内置类型。
as 如果可能,将值转换为给定类型。
self 引用当前类实例。
tool 在编辑器中执行脚本。
signal 定义一个信号。
func 定义一个函数。
static 定义一个静态函数。静态成员变量是不允许的。
const 定义一个常量。
enum 定义一个枚举。
var 定义一个变量。
onready 在脚本所附加的节点及其子节点成为场景树的一部分后初始化变量。
export 保存一个变量及其附加的资源,并使其在编辑器中可见和可修改。
setget 为变量定义setter和getter函数。
breakpoint 调试器断点的编辑器助手。
preload 预加载类或变量。请参见 Classes as resources.
yield 协同程序支持。参见 Coroutines with yield.
assert 声明一个条件,在失败时记录错误。在非调试构建中被忽略。参见 Assert keyword.
remote 网络RPC注释。参见 high-level multiplayer docs.
master 网络RPC注释。参见 high-level multiplayer docs.
puppet 网络RPC注释。参见 high-level multiplayer docs.
remotesync 网络RPC注释。参见 high-level multiplayer docs.
mastersync 网络RPC注释。参见 high-level multiplayer docs.
puppetsync 网络RPC注释。参见 high-level multiplayer docs.
PI 圆周率常量。
TAU TAU 常量。
INF 无穷大常数。用于比较。
NAN NAN(不是一个数字)常数。用于比较。
运算符

下面是支持运算符的列表及其优先级。

运算符 描述
x[index] 索引,最高优先级
x.attribute 属性引用
is 实例类型属性面板
~ 按位取反
-x 负/一元否定
* / % 乘法/除法/余数这些操作符具有与C++相同的行为。整数除法被截断,而不是返回一个小数,%运算符只对整数可用(浮点数用“fmod”)
+ 加法/数组的串联
- 减法
<< >> 位移位
& 按位与
^ 按位异或
按位或
< > == != >= <= 比较
in 内容测试
! not 布尔NOT
and && 布尔AND
or 布尔OR
if x else 三元 if/else
= += -= *= /= %= &= 赋值,最低优先级
字面量
字面量 类型
45 基数为10的整数
0x8F51 基数16(十六进制)整数
3.14, 58.1e-10 浮点数(实数)
“Hello”, “Hi” 字符串
“”“您好”"" 多行字符串
@“Node/Label” 节点路径和字符串名称
$NodePath get_node(“NodePath”) 的速记
注释

任何从 # 开始到行尾的内容都会被忽略,并被视为注释。
可以在文本块的开头和结尾使用”“”(一行三个引号)创建多行注释。注意,这将创建一个字符串,因此,在编译脚本时它不会被删除。

内置类型

Built-in types are stack-allocated. They are passed as values. This means a copy is created on each assignment or when passing them as arguments to functions. The only exceptions are Arrays and Dictionaries, which are passed by reference so they are shared. (Not PoolArrays like PoolByteArray though, those are passed as values too, so consider this when deciding which to use!)

内置类型是堆栈分配的。它们作为值传递。这意味着在每次赋值或将赋值作为参数传递给函数时都会创建一个副本。唯一的例外是 数组 s 和 字典 ,它们是通过引用传递的,所以它们是共享的。(不是像 PoolArrays PoolByteArray 那样,这些也是作为值传递的,所以在决定使用哪个时要考虑这个!

基本内置类型

GDScript中的变量可以分配给多个内置类型。

null

null 是一个空数据类型,不包含任何信息,不能分配任何其他值。

bool

布尔数据类型只能包含 true 或 false。

int

整数数据类型只能包含整数(包括负数和正数)。

float

用于包含浮点值(实数)。

String

Unicode格式 中的字符序列。字符串可以包含 标准C转义序列 。GDScript支持 格式化字符串即printf功能。

内置向量类型

Vector2

2D向量类型包含 x 和 y 字段,也可以像数组一样访问。

Rect2

二维矩形类型包含两个向量字段: position 和 size。或者包含一个 end 字段,该字段是 position+size。

Vector3

3D向量类型包含 x , y 与 z 字段,也能够像数组一样访问。

Transform2D

用于二维变换的3x2矩阵。

Plane

3D平面类型的标准形式包含一个 normal 法向量字段以及一个 d 距离标量。

Quat

四元数是一种用于表示3D旋转的数据类型。它对于内插旋转很有用。

AABB

轴向包围框(或3D框)包含两个向量字段: position 和 size。或者包含一个 end 字段,该字段是 position+size。

Basis

3×3矩阵被用于3D旋转与缩放,其包含3个向量字段(x, y 和 z) 并且可以像3D向量组那样访问。

Transform

三维变换包含一个基字段 basis 和一个向量字段 origin。

引擎内置类型

Color

颜色数据类型包含 r, g, b, 和 a 字段。它也可以作为 h, s, 和 v 来访问色相/饱和度/值。

NodePath

编译路径,到一个主要用在场景系统中的节点。它可以很容易地分配给字符串,或用字符串赋值。

RID

资源ID(RID)。服务器使用通用的RID来引用不透明数据。

Object

任何非内置类型的基类。

容器内置类型
数组

Generic sequence of arbitrary object types, including other arrays or dictionaries (see below). The array can resize dynamically. Arrays are indexed starting from index 0. Starting with Godot 2.1, indices may be negative like in Python, to count from the end.

任意对象类型的泛型序列,包括其他数组或字典(见下文)。数组可以动态调整大小。数组从索引 0 开始建立索引。从Godot 2.1开始,索引可能是负的,就像在Python中一样,从尾部开始计数。

var arr = []
arr = [1, 2, 3]
var b = arr[1] # This is 2.
var c = arr[arr.size() - 1] # This is 3.
var d = arr[-1] # Same as the previous line, but shorter.
arr[0] = "Hi!" # Replacing value 1 with "Hi!".
arr.append(4) # Array is now ["Hi!", 2, 3, 4].

GDScript arrays are allocated linearly in memory for speed. Large arrays (more than tens of thousands of elements) may however cause memory fragmentation. If this is a concern, special types of arrays are available. These only accept a single data type. They avoid memory fragmentation and also use less memory but are atomic and tend to run slower than generic arrays. They are therefore only recommended to use for large data sets:

GDScript数组在内存中按速度线性分配。然而,大型数组(超过数万个元素)可能导致内存碎片。如果一个值得关注的特殊类型的数组是可用的。它们只接受单个数据类型。它们能避免内存碎片,并且使用较少的内存,但是是原子型的,并且通常比通用数组运行得慢。因此,它们只推荐用于大数据集:

名字 解释
PoolByteArray: 一个字节数组(从0到255的整数).
PoolIntArray: 一个整数数组.
PoolRealArray: 一个浮动数组.
PoolStringArray: 一个字符串数组.
PoolVector2Array: 一个 Vector2 对象的数组.
PoolVector3Array: 一个 Vector3 对象数组.
PoolColorArray: 一个 Color 对象的数组.
字典

包含唯一关键字引用的值的关联容器

var d = {4: 5, "A key": "A value", 28: [1, 2, 3]}
d["Hi!"] = 0
d = {
    22: "value",
    "some_key": 2,
    "other_key": [2, 3, 4],
    "more_key": "Hello"
}

还支持Lua风格的表语法。Lua-style使用 = 而不是 : ,并且不使用引号来标记字符串键(这样写起来会稍微少一些)。但是请注意,与任何GDScript标识符一样,以这种形式编写的键不能以数字开头。

var d = {
    test22 = "value",
    some_key = 2,
    other_key = [2, 3, 4],
    more_key = "Hello"
}

若要向现有字典添加键,请像访问现有键一样访问它,并给它赋值:

var d = {} # Create an empty Dictionary.
d.waiting = 14 # Add String "Waiting" as a key and assign the value 14 to it.
d[4] = "hello" # Add integer 4 as a key and assign the String "hello" as its value.
d["Godot"] = 3.01 # Add String "Godot" as a key and assign the value 3.01 to it.
数据

变量可以作为类成员存在,也可以作为函数的局部变量存在。它们是用 var 关键字创建的,并且可以在初始化时指定一个值。

var a # Data type is 'null' by default.
var b = 5
var c = 3.8
var d = b + c # Variables are always initialized in order.

变量可以选择具有类型规范。指定类型时,变量将被迫始终保持相同的类型,试图分配不兼容的值将引发错误。

类型在变量声明中使用“:”(冒号)符号在变量名后面指定,后面是类型。

var my_vector2: Vector2
var my_node: Node = Sprite.new()
转换

分配给类型化变量的值必须具有兼容的类型。如果需要强制某个值为某种类型,特别是对象类型,则可以使用类型转换操作符 as。

如果值属于相同类型或类型转换的子类型,则在相同对象上进行对象类型之间的转换。

var my_node2D: Node2D
my_node2D = $Sprite as Node2D # Works since Sprite is a subtype of Node2D

如果该值不是子类型,则强制转换操作将导致“null”值。

var my_node2D: Node2D
my_node2D = $Button # Results in 'null' since a Button is not a subtype of Node2D

对于内置类型,如果可能,它们将被强制转换,否则引擎将引发错误

var my_int: int
my_int = "123" as int # The string can be converted to int
my_int = Vector2() as int # A Vector2 can't be converted to int, this will cause an error
常量

常量与变量类似,但必须是常量或常量表达式,并且必须在初始化时分配

const A = 5
const B = Vector2(20, 20)
const C = 10 + 20 # Constant expression.
const D = Vector2(20, 30).x # Constant expression: 20
const E = [1, 2, 3, 4][0] # Constant expression: 1
const F = sin(20) # sin() can be used in constant expressions.
const G = x + 20 # Invalid; this is not a constant expression!
const H = A + 20 # Constant expression: 25

虽然常量的类型是从指定的值推断出来的,但是也可以添加显式的类型规范:

const A: int = 5
const B: Vector2 = Vector2()

分配不兼容类型的值将引发错误。

枚举

枚举基本上是常量的简写,如果您想为某个常量分配连续整数,那么枚举非常有用。
如果将名称传递给枚举,它会把所有的key放在这个名字的常量字典里

enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
# Is the same as:
const TILE_BRICK = 0
const TILE_FLOOR = 1
const TILE_SPIKE = 2
const TILE_TELEPORT = 3

enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
# Is the same as:
const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}
# Access values with State.STATE_IDLE, etc.
函数

函数总是属于 class 。优先考虑变量查找范围:本地→类成员→全局。 self 变量总是可用的,并作为访问类成员的选项提供,但并不总是必需的(与Python不同, 不 应该将它作为函数的第一个参数发送)。

func my_function(a, b):
    print(a)
    print(b)
    return a + b  # Return is optional; without it 'null' is returned.  返回值非强制,缺省返回null

函数可以在任何时候 return 。默认返回值是 null。

函数还可以具有参数和返回值的类型规范。参数的类型可以类似于变量的方式添加:

func my_function(a: int, b: String):
    pass

函数的返回类型可以在参数列表之后使用箭头标记(->)指定:

func my_int_function() -> int:
    return 0

有返回类型的函数 必须 返回正确的值。将类型设置为 void 意味着函数不返回任何内容。Void函数可以使用 return 关键字提前返回,但不能返回任何值。

void_function() -> void:
    return # Can't return a value

非void函数必须 总是 返回一个值,所以如果您的代码有分支语句(例如 if/else 构造),那么所有可能的路径都必须返回一个值。例如,如果在 if 块中有一个 return ,但在 if 块之后没有,编辑器就会抛出一个错误,因为如果没有执行这个块,函数就不会有一个返回的有效值

引用函数

Contrary to Python, functions are not first class objects in GDScript. This means they cannot be stored in variables, passed as an argument to another function or be returned from other functions. This is for performance reasons.
To reference a function by name at runtime, (e.g. to store it in a variable, or pass it to another function as an argument) one must use the call or funcref helpers:

与Python相反,函数不是GDScript中的第一类对象。这意味着它们不能存储在变量中,不能作为参数传递给另一个函数,也不能从其他函数返回。这是出于性能原因。

若要在运行时按名称引用一个函数(例如,将其存储在一个变量中,或将其作为参数传递给另一个函数),必须使用 call 或funcref 帮忙:

# Call a function by name in one step.
my_node.call("my_function", args)

# Store a function reference.
var my_func = funcref(my_node, "my_function")
# Call stored function reference.
my_func.call_func(args)

你可能感兴趣的:(游戏引擎)