Cosgrove just appeared in an L.A. courtroom ... where a judge ordered Joshua Stockton to stay at least 100 yards away from the "iCarly" actress and not contact her for the next 3 years. He also has to turn in any weapons.
Stockton showed up to court wearing a big, black fur coat and a white bandana ... and seemed disoriented -- when the judge asked his age, Stockton had to check his drivers license.
We broke the story ... Cosgrove claimed Stockton stalks her wherever she goes ... and sent her chilling messages threatening suicide -- including frightening pics of a slit wrist.
In court docs, The 21-year-old actress said Stockton is "not living in the real world" ... and is not only a danger to himself ... but to her as well. The judge agreed.