Menu
CoddyTech

在 match 中使用枚举

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

match 语句可以将一个值与枚举选项进行比较。每个模式都是一个选项,写法是使用它的枚举名称:

enum Light { RED, YELLOW, GREEN }

func _ready():
	var light := Light.YELLOW
	match light:
		Light.RED:
			print("Stop")
		Light.YELLOW:
			print("Slow down")
		Light.GREEN:
			print("Go")

这会打印 Slow down。和每个 match 一样,多个选项可以用逗号分隔,共用一个分支,_ 会匹配其他所有情况:

match light:
	Light.RED, Light.YELLOW:
		print("Wait")
	_:
		print("Go")

返回值的函数需要在每条路径上都有一个 return。即使各个分支涵盖了所有选项,GDScript 仍会报告 Not all code paths return a value,除非 match 有一个 _ 分支,或者后面跟着一个 return:

func next_light(light: Light) -> Light:
	match light:
		Light.RED:
			return Light.GREEN
		Light.GREEN:
			return Light.YELLOW
		_:
			return Light.RED

参数和返回类型都是枚举 Light。函数和枚举一样,在顶层声明。

challenge icon

挑战

简单

脚本声明了枚举 State,其中包含选项 IDLE、WALK、RUN、JUMP 和 FALL。请完成函数 describe():它接收一个状态,并通过 match 选择并返回对应的描述:

  • State.IDLE:"Standing still"
  • State.WALK 和 State.RUN:"Moving"
  • State.JUMP 和 State.FALL:"In the air"

为 WALK 和 RUN 使用同一个分支,为 JUMP 和 FALL 使用同一个分支。给定代码中的 _ready() 会读取一行状态名称,并打印每个状态及其描述。对于输入 IDLE RUN FALL,输出为:

IDLE: Standing still
RUN: Moving
FALL: In the air

亲手试试

extends Node

enum State { IDLE, WALK, RUN, JUMP, FALL }

func describe(state: State):
	# 使用 match 返回状态的描述
	pass

func _ready():
	var names := OS.read_string_from_stdin().split(" ", false)
	for state_name in names:
		print(state_name, ": ", describe(State[state_name]))
quiz icon自我测试

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

逻辑与流程中的所有课

自己练习: GDScript 在线编译器