Using local variable outside its chunk in Lua?

别说谁变了你拦得住时间么 提交于 2020-04-16 05:00:29

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/60855258/using-local-variable-outside-its-chunk-in-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!