How to execute at a player holding a specific item in Minecraft? [duplicate]

I'm trying to direct /execute to the location of a player who is holding a specific item. In this case, an item with the name "Gun". This is the script I'm trying to use:

/execute @e {SelectedItem:{tag:{display:{Name:"Firestarter"}}}} ~ ~ ~ 
/summon Fireball ~ ~ ~ {ExplosionPower:0,direction:[0.0,0.0,0.0]}

Unfortunately, this doesn't work. I've compiled the script from two working scripts:

/execute @p ~ ~ ~ 
/summon Fireball ~ ~ ~ {ExplosionPower:0,direction:[0.0,0.0,0.0]}

and

/testfor @e {SelectedItem:{tag:{display:{Name:"Gun"}}}}

Does anyone know how to put these together? The output of the command block is "that entity cannot be found"


Solution 1:

Contrary to other commands, like testfor, the execute command does not support data tag matching. The syntax is:

execute <entity> <x> <y> <z> <command …> 

Luckily, you can turn data tag matching into a scoreboard objective, as detailed in this answer. Set up a scoreboard objective using

scoreboard objectives add hasGun dummy

Create a fast clock (setblock/fill clock recommended), and run the following two commands (at the same time, but in this order!):

scoreboard players set @a hasGun 0
scoreboard players set @a hasGun 1 {SelectedItem:{tag:{display:{Name:"Firestarter"}}}}

You can now use this this objective in a target selector, such as

execute @a[score_hasGun_min=1] ~ ~ ~ summon Fireball ~ ~ ~ {ExplosionPower:0,direction:[0.0,0.0,0.0]}