我正在测试Lua的范围并注意到一些意外的事情.以下代码不会打印localMainVariable. function functionScope() print( "\nIn function") print( "globalMainVariable: " .. globalMainVariable ) if (localMainVariable ~= nil) the
function functionScope() print( "\nIn function") print( "globalMainVariable: " .. globalMainVariable ) if (localMainVariable ~= nil) then print( "localMainVariable: " .. localMainVariable ) end end globalMainVariable = "Visible" local localMainVariable = "Visible" functionScope()
但是下面的代码确实打印了localMainVariable.
globalMainVariable = "Visible" local localMainVariable = "Visible" function functionScope() print( "\nIn function") print( "globalMainVariable: " .. globalMainVariable ) if (localMainVariable ~= nil) then print( "localMainVariable: " .. localMainVariable ) end end functionScope()
我知道它与声明localMainVariable的位置有关,但我认为将其设置为local会限制变量的范围.什么是实际规则?
谢谢
The scope of a local variable begins at the first statement after its
declaration and lasts until the last non-void statement of the
innermost block that includes the declaration.
Lua manual