I'd honestly convert it to a loop.
Lua Code:
function BattleDex.RecordBattle()
if not C_PetBattles.IsWildBattle() then return; end
local primary=0;
for i=1,C_PetBattles.GetNumPets(2) do
local species=C_PetBattles.GetPetSpeciesID(2,i);
BattleDex.RecordPet(
species
,C_PetBattles.GetLevel(2,i)
,C_PetBattles.GetBreedQuality(2,i)
,primary-- Passes zero for the first iteration
);
if i==1 then primary=species; end-- Sets the primary species for following iterations
end
end