lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]





On Mon, Aug 26, 2013 at 4:00 PM, Tim Hill <drtimhill@gmail.com> wrote:

I don't think this is quite as simple as all that. Consider this:

local a = 1
function foo()
        return a
end
local a = 2
print(foo())

Clearly, foo() prints 2, as it should...
--Tim


Hmm... not in my world. It returns 1 as I think it should.

However:

local a = 1
function foo()
        return a
end
 a = 2
print(foo())
--> 2

When you declare a variable with local local, you make a _new_ variable. You do not overwrite the old one. The second local declaration in your code is not lexically in scope of foo, so why would it overwrite it?

When you set a variable without local, you assign a new value to the existing variable, if it exists, or to the _G/_ENV table, if it does not. 


-Andrew