Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scoping rules in Lua

Tags:

scope

lua

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

like image 334
user2202829 Avatar asked Mar 23 '13 17:03

user2202829


1 Answers

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

like image 56
Egor Skriptunoff Avatar answered Dec 31 '22 19:12

Egor Skriptunoff