Search code examples
if-statementvariableslualocal-variables

Using local variable outside its chunk in Lua?


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?


Solution

  • Technically the answer is no, you can't use a local variable outside its scope, that's the whole point of local variables. However, you can just change the scope of the variable by declaring it outside of the block where you're using it:

    local foo
    if io.read() == "hello" then -- Just a dumb example condition :)
       foo = "hello" -- This is not a global, as it was declared local above
    end
    print(foo)
    

    However, note that the the following doesn't work, or, more precisely, doesn't do the same as the above:

    local foo
    if io.read()=="hello" then
       local foo = "hello" -- This is another local
    end
    print(foo) -- This will *always* print nil