Page 1 of 1

recipe by name

Posted: Tue Dec 29, 2015 8:12 pm
by matjojo
When a player crafts an item the game triggers the event "on_player_crafted_item". In that even you get the variable item_stack. So, you have the items name with "event.item_stack.name". How does one get the recipe class of the achieved name.

I tried a couple of things that (of course) didn't work. I tried just adding ".recipe" after the "item_stack" (with and without ".name"). and some other things that didn't work.

How would one get the recipe of an item if you have the name of that item?

thanks,
Matjojo

Re: recipe by name

Posted: Tue Dec 29, 2015 8:22 pm
by DaveMcW
You need to search player.force.recipes for a matching item.

Code: Select all

function get_recipe(player, item)
  for _, recipe in pairs(player.force.recipes) do
    for _, product in pairs(recipe.products) do
      if (product.name == item) then
        return recipe.name
      end
    end
  end
  return nil
end
Note that it's possible for an item to have more than one recipe.

Re: recipe by name

Posted: Fri Jan 01, 2016 2:01 pm
by matjojo
DaveMcW wrote:You need to search player.force.recipes for a matching item.
snippy snippet
Thanks, that worked. I figured I needed to call the function like this:

Code: Select all

get_recipe(game.player, event.item_stack.name)
and that worked.

now, you pointed out that there are items with more then one recipe, would you know a way to make sure you have the right recipe selected?