mercredi 25 mars 2020

Using local variable outside its chunk in Lua?

I have this code in Lua

  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)

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?

Aucun commentaire:

Enregistrer un commentaire