Membership
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 75 of 92.
The in operator checks whether a value is an element of an array. It returns true or false; not in returns the opposite:
var pets := ["cat", "dog"]
print("cat" in pets)
print("fox" not in pets)
print("fox" in pets)true
true
falseArrays also have methods for searching:
has(value)returnstrueif the value is in the array, likeinfind(value)returns the index of the first matching element, or-1if there is nonecount(value)returns how many elements are equal to the value
var drops := ["coin", "gem", "coin"]
print(drops.has("gem"))
print(drops.find("coin"))
print(drops.find("key"))
print(drops.count("coin"))true
0
-1
2On strings, in looks for text inside the string: "ell" in "hello" is true.
Challenge
EasyThe program reads two lines of values separated by commas into the arrays first and second (already written).
Print a new array with every element of first that is not in second, in the order of first. Keep duplicates. For the inputs 1,2,3,4,5 and 2,4,6, the output is:
["1", "3", "5"]Try it yourself
extends Node
func _ready():
var first := OS.read_string_from_stdin().split(",")
var second := OS.read_string_from_stdin().split(",")
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler