I was testing the scope for Lua and noticed something unexpected. The following code does not print the localMainVariable.
function functionScope()
print( "\nIn function")
print( "globalMainVariable: " .. globalMainVariable )
if (localMainVariable ~= nil) then print( "localMainVariable: " .. localMainVariable ) end
end
globalMainVariable = "Visible"
local localMainVariable = "Visible"
functionScope()
But the following code does print localMainVariable.
globalMainVariable = "Visible"
local localMainVariable = "Visible"
function functionScope()
print( "\nIn function")
print( "globalMainVariable: " .. globalMainVariable )
if (localMainVariable ~= nil) then print( "localMainVariable: " .. localMainVariable ) end
end
functionScope()
I know it has something to do with where the localMainVariable was declared, but I thought making it local would limit the scope of the variable. What is the actual rule?
Thanks
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With