I have a nested if in Lua. I have a variable inside the second if layer that I want to use in the first layer.
The variable is npcSpecimen.
if conditions then
  local npcType = util.pickRandom(self.npcTypes)
  local npcSpecimen = "" 
  
  if npcType == "spacebandit" then
    local npcSpecimen = util.pickRandom(self.npcSpecies)
  else
    local npcSpecimen = util.pickRandom(self.npcSpeciesMutant)
  end
  local npcId = space.spawnNpc(spawnPosition, npcSpecimen, npcType)
end
If written this way, npcSpecimen will remain empty because the variable set within the if npcType remains only within that chunk. So to alleviate this, I could use global variable instead:
  if npcType == "spacebandit" then
    npcSpecimen = util.pickRandom(self.npcSpecies)
  else
    npcSpecimen = util.pickRandom(self.npcSpeciesMutant)
  end
However according to the documentation, using global variable isn't the best practice and it's slower.
So what would be the best way to approach this so I could pass npcSpecimen to npcId?
local npcSpecimen =withnpcSpecimen =. The variable stays local due to its definitionlocal npcSpecimen = ""