I've got the National D visa for Hungary for studies. I am from Peru. The best price for me is taking Air Europa Lima-Madrid-Amsterdam ticket and from there I would need to change of terminal, take my luggage to take the another ticket KLM to Budapest. Is that possible to do with a D national visa?
In principle, there should not be any problem as your type D visa allows you to enter the Schengen area and visit other countries (up to 90 days in a 180-day period).
However, your visa needs to be valid (i.e. you can only use it after the day it starts to be valid in Hungary, you can't plan your trip to arrive just in time in Budapest). If border guards wonder why you are going to the Netherlands instead of Hungary, simply being able to show your other ticket should be enough to alleviate their concerns but having something proving you are registered as a student and your studies start later cannot hurt either, just in case.
Note that your visa situation will be checked when boarding in Peru, long before you come to the passport check in Madrid. If you have a valid type D visa, the airline should not make any problem but that will be the biggest hurdle. Once you entered the Schengen area in Madrid, you most likely won't be checked anymore (i.e. not on landing in Amsterdam and also not when taking your flight to Budapest or landing there). You do have to show ID to the handling personnel to check in and board the KLM flight but there should not be any systematic police check.