静态类型
int a; // Value uninitialized
a = 5; // This is valid
a = "Hi!"; // This is invalid
void print_value(int value) {
printf("value is %i\n", value);
}
print_value(55); // Valid
print_value("Hello"); // Invalid
动态类型
var a # null by default
a = 5 # Valid, 'a' becomes an integer
a = "Hi!" # Valid, 'a' changed to a string
func print_value(value):
print(value)
print_value(55) # Valid
print_value("Hello") # Valid
指针 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
}
引用 GDScript
func use_class(instance); # Does not care about class type
instance.use() # Will work with any class that has a ".use()" method.
func do_something():
var instance = SomeClass.new() # Created as reference
use_class(instance) # Passed as reference
# Will be unreferenced and deleted
数组创建
int *array = new int[4]; // Create array
array[0] = 10; // Initialize manually
array[1] = 20; // Can't mix types
array[2] = 40;
array[3] = 60;
// Can't resize
use_array(array); // Passed as pointer
delete[] array; // Must be freed
std::vector<int> array;
array.resize(4);
array[0] = 10; // Initialize manually
array[1] = 20; // Can't mix types
array[2] = 40;
array[3] = 60;
array.resize(3); // Can be resized
use_array(array); // Passed reference or value
// Freed when stack ends
var array = [10, "hello", 40, 60] # Simple, and can mix types
array.resize(3) # Can be resized
use_array(array) # Passed as reference
# Freed when no longer in use
var array = []
array.append(4)
array.append(5)
array.pop_front()
var a = 20
if a in [10, 20, 30]:
print("We have a winner!")
字典
var d = {"name": "John", "age": 22} # Simple syntax
print("Name: ", d["name"], " Age: ", d["age"])
d["mother"] = "Rebecca" # Addition
d["age"] = 11 # Modification
d.erase("name") # Removal
var d = {
name = "John",
age = 22
}
print("Name: ", d.name, " Age: ", d.age) # Used "." based indexing
d["mother"] = "Rebecca"
d.mother = "Caroline" # This would work too to create a new key
循环
const char* strings = new const char*[50];
for (int i = 0; i < 50; i++){
printf("Value: %s\n", i, strings[i]);
}
// Even in STL:
for (std::list<std::string>::const_iterator it = strings.begin(); it != strings.end(); it++) {
std::cout << *it << std::endl;
}
for s in strings:
print(s)
for key in dict:
print(key, " -> ", dict[key])
for i in range(strings.size()):
print(strings[i])
range(n) # Will go from 0 to n-1
range(b, n) # Will go from b to n-1
range(b, n, s) # Will go from b to n-1, in steps of s
for (int i = 0; i < 10; i++) {}
for (int i = 5; i < 10; i++) {}
for (int i = 5; i < 10; i += 2) {}
for i in range(10):
pass
for i in range(5, 10):
pass
for i in range(5, 10, 2):
pass
for (int i = 10; i > 0; i--) {}
for i in range(10, 0, -1):
pass
var i = 0
while i < strings.size():
print(strings[i])
i += 1
自定义迭代器
class FwdIterator:
var start, curr, end, increment
func _init(start, stop, inc):
self.start = start
self.curr = start
self.end = stop
self.increment = inc
func is_done():
return (curr < end)
func do_step():
curr += increment
return is_done()
func _iter_init(arg):
curr = start
return is_done()
func _iter_next(arg):
return do_step()
func _iter_get(arg):
return curr
var itr = FwdIterator.new(0, 6, 2)
for i in itr:
print(i) # Will print 0, 2, and 4
检测是否有对应函数
func _on_object_hit(object):
if object.has_method("smash"):
object.smash()
不要用错缩进
#good
for i in range(10):
print("hello")
#bad
for i in range(10):
print("hello")
#good
effect.interpolate_property(sprite, 'transform/scale',
sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
Tween.TRANS_QUAD, Tween.EASE_OUT)
#bad
effect.interpolate_property(sprite, 'transform/scale',
sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
Tween.TRANS_QUAD, Tween.EASE_OUT)
#good
if position.x > width:
position.x = 0
if flag:
print("flagged")
#bad
if position.x > width: position.x = 0
if flag: print("flagged")
#good
if is_colliding():
queue_free()
#bad
if (is_colliding()):
queue_free()
#good
position.x = 5
position.y = mpos.y + 10
dict['key'] = 5
myarray = [4, 5, 6]
print('foo')
#bad
position.x=5
position.y = mpos.y+10
dict ['key'] = 5
myarray = [4,5,6]
print ('foo')
#never
x = 100
y = 100
velocity = 500
命名空间
const MyCoolNode = preload('res://my_cool_node.gd')
中断
signal door_opened
signal score_changed
格式化字符串
# Define a format string with placeholder '%s'
var format_string = "We're waiting for %s."
# Using the '%' operator, the placeholder is replaced with the desired value
var actual_string = format_string % "Godot"
print(actual_string)
# Output: "We're waiting for Godot."
# Define a format string
var format_string = "We're waiting for {str}"
# Using the 'format' method, replace the 'str' placeholder
var actual_string = format_string.format({"str": "Godot"})
print(actual_string)
# Output: "We're waiting for Godot"
var format_string = "%s was reluctant to learn %s, but now he enjoys it."
var actual_string = format_string % ["Estragon", "GDScript"]
print(actual_string)
# Output: "Estragon was reluctant to learn GDScript, but now he enjoys it."
字符
符号 | 意义 |
---|---|
s | 替换字符串,Simple conversion to String by the same method as implicit String conversion. |
c | 替换字符,A single Unicode character. Expects an unsigned 8-bit integer (0-255) for a code point or a single-character string. |
d | 整数,A decimal integral number. Expects an integral or real number (will be floored). |
o | 10进制整数,An octal integral number. Expects an integral or real number (will be floored). |
x | 小写字母16进制,A hexadecimal integral number with lower-case letters. Expects an integral or real number (will be floored). |
X | 大写字母16进制,A hexadecimal integral number with upper-case letters. Expects an integral or real number (will be floored). |
f | 小数,A decimal real number. Expects an integral or real number. |
格式化事例
10位或以下整数
print("%10d" % 12345)
# output: " 12345"
10位整数,补零
print("%010d" % 12345)
# output: "0000012345"
保留三位小数
print("%10.3f" % 10000.5555)
# Output: " 10000.556"
保留长度
print("%-10d" % 12345678)
# Output: "12345678 "
配置和值都做成动态
var format_string = "%*.*f"
# Pad to length of 7, round to 3 decimal places:
print(format_string % [7, 3, 8.8888])
# Output: " 8.889"
#相当于%7.3f
print("%0*d" % [2, 3])
#output: "03"
#相当于%02d
输出转义字符原符号
var health = 56
print("Remaining health: %d%%" % health)
# Output: "Remaining health: 56%"