Force balance teams

Hey, I cannot test this code for my friend, and I know there is a better way to code this, this is basically what I coded
[lua]
function GM:ShowTeam( ply )
if ply:Team() == 1 and team.NumPlayers( 2 ) < team.NumPlayers( 1 ) then
umsg.Start( “set_team”, ply )
umsg.End()
elseif ply:Team() == 2 and team.NumPlayers( 1 ) < team.NumPlayers( 2 ) then
umsg.Start( “set_team”, ply )
umsg.End()
else PrintMessage( HUD_PRINTTALK, “Teams are already balanced” )

end
end

function GM:PlayerInitialSpawn( ply )
if team.NumPlayers( 1 ) > team.NumPlayers( 2 ) then
ply:SetTeam( 2 )
elseif team.NumPlayers( 2 ) > team.NumPlayers( 1 ) then
ply:SetTeam( 1 )
else
RunConsoleCommand( “team_menu” )
end
end
[/lua]

the umsg.Start( “set_team”, ply ) opens the derma to change teams, the derma is just 2 buttons with red and blue, red puts you to red team and blue to blue team

Basically, what I believe I have setup is that when they join they are assigned to the team with least players, else they get to choose there team
and If they press F2 which opens the derma, it checks if the teams are balanced if not allows the menu else tells client they cannot change teams

The reason I am making this post is because I am fairly new to lua, I wrote that from scratch so I don’t know if it works, I cannot test if it works for a few hours, and knowing me, there is most likely a very easier and better way to do this.