Location Rules in Lua

I tested the scope for Lua and noticed something unexpected. The following code does not print 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 prints 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 this has something to do with where localMainVariable is declared, but I thought making it local would limit the scope of the variable. What is the actual rule?

thanks

+4
source share
1 answer

The scope of a local variable begins with the first statement after its declaration and continues until the last non-military statement, the innermost block including the declaration.

Lua Guide

+4
source

All Articles