- The correct title of this article is Item # of () in (). The Scratch Wiki uses this different title because of technical restrictions.
Item # of () in () | |
(item # of [] in [ v]) | |
Category | List |
Type | Reporter |
Introduced in | 3.0 |
Item Number of () in () is a list block and a reporter block. This block reports the index in a list where an item first appears. If an item appears more than once, it reports the index of the first occurrence of that item. If the item is not in a list, it reports 0. It is one of only two reporter blocks that can be inserted into a boolean input, the other one being the Item () of () (block) block.
Example
when gf clicked delete all of [list v] add [a] to [list v] add [b] to [list v] add [c] to [list v] add [b] to [list v] say (item # of [c] in [list v]) //says 3 since c is the third item in the list say (item # of [b] in [list v]) //says 2 since the first occurrence of b in the list is in the second position say (item # of [d] in [list v]) //says 0 since d is not in the list
Workaround
This can instead be accomplished by looking at each item in a list in order and seeing if any of them equal the item being searched for:
define item # of (search term) in list set [counter v] to (0) set [result v] to (0) repeat (length of [list v]) change [counter v] by (1) if <(item (counter) of [list v])=(search term)> then set [result v] to (counter) stop [this script v] end end
or
define item # of (string) in list set [result v] to [0] if <[list v] contains (string)?> then repeat until <(item (result) of [list v]) = (string)> change [result v] by (1) end end
In a Boolean Input
This block can be inserted into a boolean input, despite being a reporter block. This is the only block with this special property, aside from Item () of ().
Because all numbers are converted to true
except for 0, the block only returns true when inputted string is present in the list. This is equivalent to the <[ v] contains []?>
block, making the fact that this block can be in a boolean input rather useless.
Related Suggestion
Some Scratchers want an operators block that reports the appearance of a string in another.[1] Such a block would look like this:
(letter # of () in ():: operators)
However, it can be worked around by this code:
define letter # of (letter) in (string) set [counter v] to (0) set [result v] to (0) repeat (length of (string)) change [counter v] by (1) if <(letter (counter) of (string))=(letter)> then set [result v] to (counter) stop [this script v] end end
Note: | Only works if the length of letter is 1. |
See Also
References
- ↑ codeman1044. (2019-05-18). "letter # of () in () [title]" topic:351646