NAIROBI, Kenya — After months of heated, sometimes violent debate, Uganda’s Parliament voted late Wednesday to lift the age limit for the presidency, setting the stage for President Yoweri Museveni to rule the country indefinitely.

Mr. Museveni is in his fifth presidential term, which expires in 2021. By then, he will be 77 — two years past the age limit for a president set by Uganda’s 1995 Constitution.

A majority of lawmakers supported the bill, which passed 315 to 62 late Wednesday night, but a majority of Ugandans opposed it. A September poll by Afrobarometer found that 75 percent of respondents wanted to keep the age limit.

Once Mr. Museveni signs the bill, it will become law. It is expected to be challenged in court.

The final days of parliamentary debate on the bill included accusations that soldiers were hiding inside Parliament’s chapel, where some lawmakers said they uncovered dishware and bottles filled with urine, suggesting that the soldiers may have planned an extended stay.