If you want to use it in a theme, try putting it in a function wrapper and then calling that function in your template. In functions.php:
function bbg_forum_pag() {
global $forum_template;
$per_page = 5;
$total_posts = $forum_template->topic->topic_posts;
$pag_links = paginate_links( array(
'base' => add_query_arg( array( 'topic_page' => '%#%', 'num' => (int) $per_page ), bp_get_the_topic_permalink() ),
'format' => '',
'total' => ceil( (int) $total_posts / (int) $per_page ),
'mid_size' => 1
) );
echo $pag_links;
}
Then in your template:
<?php bbg_forum_pag() ?>