Same-sex couples from states where gay marriage is banned cannot legally marry in Massachusetts, the state's highest court ruled Thursday.

The Supreme Judicial Court, which three years ago made Massachusetts the first state to legalize gay marriage, upheld a 1913 state law that forbids nonresidents from marrying in Massachusetts if their marriage would not be recognized in their home state.

"The laws of this commonwealth have not endowed non-residents with an unfettered right to marry," the court wrote in its 38-page opinion. "Only non-resident couples who come to Massachusetts to marry and intend to reside in this commonwealth thereafter can be issued a marriage license without consideration of any impediments to marriage that existed in their former home states."

Eight gay couples from surrounding states had challenged the law in a case watched closely across the country.

In Thursday's ruling, the court sent the cases involving couples from Rhode Island and New York back to a lower court, saying it was unclear whether those states prohibit same-sex marriage.

Gov. Mitt Romney applauded the ruling.

"We don't want Massachusetts to become the Las Vegas of same-sex marriage," Romney said. "It's important that other states have the right to make their own determination of marriage and not follow the wrong course that our Supreme Judicial Court put us on."

One plaintiff, Mark Pearsall, called Thursday's ruling "illogical."

"It's a statement that's not really based around any sense of humanity, but really on a sense of politics, which is really not a fair way to treat people. It's a hurtful thing," said Pearsall, of Lebanon, Conn., who traded vows with Paul Trubey in Worcester in 2004.

In oral arguments before the high court in October, a lawyer for the couples argued that the 1913 law had been unused for decades, until it was "dusted off" by Romney in an attempt to discriminate against same-sex couples.

Romney ordered city and town clerks to enforce that law after the first same-sex marriages were performed in Massachusetts in May 2004.

Attorneys for the state argued that Massachusetts risked a backlash if it ignored the laws of other states by letting same-sex couples marry here when their own states prohibited such unions.

More than 6,000 gay couples have tied the knot in Massachusetts since the court ruled in 2003 that the state Constitution gives same-sex couples the same right to marry as heterosexual couples.

Christopher McCary and John Sullivan, who were among the first gay couples married in the state, said they still consider themselves married, even if Thursday's ruling means they're just two guys living in the same house in Alabama.

"It really doesn't change anything," said McCary, an attorney in Anniston. "We're like everybody else. He has two jobs, I have one and we both work all the time."

The state of Alabama does not recognize their union.