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

本文介绍了GDScript中的动态类型特性,包括变量赋值、函数参数、指针引用、数组和字典的使用。强调了动态语言与静态语言的区别,如在GDScript中,数组和字典的灵活性以及自定义迭代器的实现。同时讲解了鸭子类型的原理,简化了代码设计,允许对象只需具备特定方法即可,无需关注其继承结构。
摘要由CSDN通过智能技术生成
变量与赋值

All variables in a dynamically typed language are “variant”-like. This means that their type is not fixed, and is only modified through assignment. Example:

动态类型语言中的所有变量都是“可变”的。这意味着它们的类型不是固定的,而是通过赋值修改的。例如:

静态语言的:

int a; // Value uninitialized 变量没初始化
a = 5; // This is valid      合法
a = "Hi!"; // This is invalid   不合法

动态语言的:

var a # null by default      默认是空类型
a = 5 # Valid, 'a' becomes an integer      合法,a变成了整型
a = "Hi!" # Valid, 'a' changed to a string   合法,a改变成了字符串型

Functions are of dynamic nature too, which means they can be called with different arguments, for example:

函数参数

函数也是动态的,这意味着它们可以用不同类型的参数调用,比如:

静态语言的:

void print_value(int value) {

    printf("value is %i\n", value);
}

[..]

print_value(55); // Valid
print_value("Hello"); // Invalid

动态语言的:

func print_value(value):
    print(value)

[..]

print_value(55) # Valid
print_value("Hello") # Valid
指针与引用

In static languages, such as C or C++ (and to some extent Java and C#), there is a distinction between a variable and a pointer/reference to a variable. The latter allows the object to be modified by other functions by passing a reference to the original one.

在静态语言(如C或C++)(以及在Java和C#一定程度上),变量和指针/引用与变量之间存在区别。后者通过传递对原始函数的引用,允许其他函数修改对象。

In C# or Java, everything not a built-in type (int, float, sometimes String) is always a pointer or a reference. References are also garbage-collected automatically, which means they are erased when no longer used. Dynamically typed languages tend to use this memory model, too. Some Examples:

在C# 或Java中,不是内置类型(int,float,有时的String)的任何东西都是指针或引用。引用也是自动内存垃圾回收,这意味着它们在不再使用时被删除。动态类型的语言也倾向于使用这种内存模型。示例:

C++

void use_class(SomeClass *instance) {

    instance->use();
}

void do_something() {

    SomeClass *instance = new SomeClass; // Created as pointer
    use_class(instance); // Passed as pointer
    delete instance; // Otherwise it will leak memory
}

JAVA

@Override
public final void use_class(SomeClass instance) {

    instance.use();
}

public final void do_something() {

    SomeClass instance = new SomeClass(); // Created as reference
    use_class(instance); // Passed as reference
    // Garbage collector will get rid of it when not in
    // use and freeze your game randomly for a second
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值