A Virginia state judge ruled yesterday that a college student from Fredericksburg serving a 20-year prison sentence for a cocaine conviction was being imprisoned unlawfully and ordered him freed pending resentencing next month.

Attorneys from Alexandria who represented Robert W. Gibson, 27, argued that he should be released because a state police officer had not informed the court that he knew a key figure in the drug sale that led to Gibson's arrest and was aware he was a police informant.

Gibson, who has been in jail for a year and a half, contended that the informant had pressured him into involvement in the crime--the sale in 1980 of a pound of cocaine in a Bristol, Va., motel room for $28,000.

During a trial in Bristol, the Virginia State Police undercover officer to whom the sale was made testified he had never met the informant before the sale, according to one of Gibson's lawyers, John Zwerling.

Zwerling said the informant, identified as William Wright, disappeared after the cocaine sale but was recently located. Wright, who testified at the hearing in Bristol yesterday, has said the officer arrested him before the sale on another charge and knew he had agreed to work for the police.

Wright was arrested in California two months ago and extradited to Virginia to testify at yesterday's proceedings, Zwerling said.

After the testimony, Circuit Court Judge Charles B. Flannagan freed Gibson on $10,000 bond. He is to be resentenced at a hearing scheduled for Aug. 25.

Formerly a student at East Tennessee State University, Gibson was convicted of possession of cocaine with intent to distribute. He was initially sentenced to 30 years in prison, but the term was later reduced to 20 years last summer.

His attorneys contended that though he was present at the sale, he did not handle the drug or profit from its sale. He agreed to introduce Wright to an alleged cocaine dealer, they said, because Wright often showed up at his house armed and was a "dangerous and very unpredictable person."