() Contains ()? | |
[ v] contains []? | |
Category | List |
Type | Boolean |
Introduced in | 1.4 |
- This article is about the list block. For the Operators block that checks if one string contains the other, see () Contains ()? (Operators block).
The () contains ()? block is a boolean block and a list block. The block checks if any items in the specified list is equal to the given text; if at least one of the items is equal to the specified text, the block returns true, and if none of them are, the block returns false. The specified text must be exactly equal to at least one of the items in the list; for example, the text "abc" would not be considered to be in a list with only the item "abcde".
This block used to be called "() Contains ()", or [ v] contains []:: list
, before a question mark was added to its name Scratch 2.0.[1]
This block was case sensitive in Scratch 1.4 when checking that an item is equal to the specified string, but this was changed to be a case insensitive procedure in Scratch 2.0 and beyond.
Example Uses
This block can be used to check whether an item is in a list or not.
Some common uses for the () Contains ()? block:
- Scanning lists
if <[lunch v] contains [spinach]?> then say [Yuck! Spinach!] end
- Checking if an item already exists before adding it to an inventory
if <not <[collection v] contains [fan]?>> then add [fan] to [collection v] else say [I already have a fan in my collection.] end
- Making sure an item is in an inventory before performing a command.
if <[collection v] contains [fan]?> then broadcast (action v) else say [It's too far to reach the pile of sand on that platform.] end
- Checking if a selected level is locked or unlocked for the player.
ask [which level would you like to play?] and wait if <[unlocked levels v] contains (answer)?> then broadcast(start level v) else say [The level you chose hasn't been unlocked yet! Play the previous level to play this one.
Case Sensitivity
This block was case sensitive in its checks in Scratch 1.4, but was changed to be case insensitive. This means that if a list contains exactly "apple", all of the following will report true:
<[list v] contains [APPLE]> <[list v] contains [apple]> <[list v] contains [Apple]>
Workaround
- Main article: List of Block Workarounds
This block can be replicated with the following code:
set [count v] to [1] repeat until <<(count) > (length of [list v])> or <(item (count) of [list v]) = (thing)>> change [count v] by (1) end set [report v] to <(item (count) of [list v]) = (thing)>
When it is needed,<(report) = [true]>
is placed into the boolean insert.
However, a simpler workaround is to just use the (item # of [thing] in [list v])
, which can be inserted into boolean inserts:
if (item # of (. . .:: grey) in [list v]) then . . . end