Menu
CoddyTech

所属チェック

CoddyのGDScriptジャーニー「ロジックとフロー」セクションの一部。レッスン 10/78。

すでに in と not in を使って所属を確認しています。"cat" in pets は配列内の要素を探し、"ell" in "hello" は文字列内のテキストを探します。ほかにも、よく使われるケースが3つあります。

辞書では、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 に読み込みます。

次の3行を出力します。

  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()
	# 3行を出力する
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ロジックとフローのすべてのレッスン

自分で練習してみよう: GDScriptオンラインコンパイラ