Menu
CoddyTech

成员检查

本课属于 Coddy GDScript 学习旅程的“逻辑与流程”单元。第 10 课,共 78 课。

你已经会用 in 和 not in 检查成员关系:"cat" in pets 用来查找数组中的元素,而 "ell" in "hello" 用来查找字符串中的文本。还有另外三种常见情况。

对于字典,in只检查键。要查找值,请检查values()返回的数组:

var grades := {"Alice": 85, "Bob": 90}
print("Alice" in grades)
print(90 in grades)
print(90 in grades.values())
true
false
true

成员关系也会比较数据类型。通过 OS.read_string_from_stdin() 读取的文本是字符串,而字符串 "90" 不是整数 90:

var scores := [70, 90]
print("90" in scores)
print(int("90") in scores)
false
true

使用包含允许值的常量数组和 in,可以替代一长串 or,也可以在守卫中使用:

const DIRECTIONS = ["north", "south", "east", "west"]
var dir := "west"
match dir:
	var d when d in DIRECTIONS:
		print("Going ", d)
	_:
		print("You cannot go there")
Going west
challenge icon

挑战

简单

程序有一个包含班级学生姓名的数组 names,以及一个包含已有成绩学生的字典 grades。程序会将学生姓名读入 student,并将成绩作为文本读入 grade。

打印三行:

  1. NAME is in the class. 或 NAME is not in the class.,检查 names
  2. NAME has a grade. 或 NAME has no grade.,检查 grades 的键
  3. Someone scored GRADE. 或 Nobody scored GRADE.,检查 grades 的值

将 NAME 和 GRADE 替换为输入内容。输入 Dana 和 85 时,输出为:

Dana is in the class.
Dana has no grade.
Someone scored 85.

亲手试试

extends Node

func _ready():
	var names := ["Alice", "Bob", "Charlie", "Dana"]
	var grades := {"Alice": 85, "Bob": 90, "Charlie": 78}
	var student := OS.read_string_from_stdin()
	var grade := OS.read_string_from_stdin()
	# 输出这三行
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: GDScript 在线编译器