在Lua中的块外使用局部变量? [英] Using local variable outside its chunk in Lua?
问题描述
我在Lua中有一个嵌套的if
.在第二层if
层中有一个要在第一层中使用的变量.
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.
变量是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
如果以此方式编写,npcSpecimen
将保持为空,因为if 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.
那么最好的方法是什么,以便我可以将npcSpecimen
传递给npcId
?
So what would be the best way to approach this so I could pass npcSpecimen
to npcId
?
推荐答案
技术上答案是否,您不能在范围之外使用局部变量,这就是局部变量的重点.但是,您可以通过在使用变量的块外声明变量来更改变量的范围:
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
这篇关于在Lua中的块外使用局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!