lua-users home
lua-l archive

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


I think your confusion comes from the syntactic sugar "local a = 20". You should try to expand it to understand it better. Your code becomes:

-- Syntactic sugar expansion
local a
a = 10
function f( )
	print( a )
end

local a
a = 20
function g( )
	print( a )
end -- g

a = 30     -- no local here
print( a ) --> 30
f( )       --> 10
g( )       --> 30


Here you can see that you have two and only two variable creations. That's why you have two different printed values. To understand why each print gives that result, you can simply do some variable name substitution to see what happens. From top to bottom, each time you encounter a variable creation with an already used name, rename it and each subsequent access with a unique name. Here is what it gives :

-- Syntactic sugar expansion
local a1
a1 = 10
function f( )
	print( a1 )
end

local a2
a2 = 20
function g( )
	print( a2 )
end -- g

a2 = 30     -- no local here
print( a2 ) --> 30
f( )       --> 10
g( )       --> 30

That's it. "print(a2)" prints the content of a2. f prints the content of a1 (because at the moment of f closure "a" was an alias to a1). G prints the content of a2 (because at the moment of g closure "a" was an alias to a2). It's because although being in the same file, f and g have different scopes. A pseudo C equivalent would be:

static int a = 10;
void f() {
	printf("%d\n", a);
}

static int a = 20;
void g() {
	printf("%d\n", a);
}

void main()
{
	a = 30;
	printf("%d\n", a); // -> 30
	f(); // -> 10
	g(); // -> 30
}

But in C/C++ variable redefinition in the same scope is forbidden, and you cannot create function in any other scope than the global one, so the problem cannot arise.

-----Message d'origine-----
De : lua-bounces@bazar2.conectiva.com.br [mailto:lua-bounces@bazar2.conectiva.com.br] De la part de Nick Gammon
Envoyé : 7 septembre 2006 17:49
À : Lua list
Objet : Re: Forward declarations in modules


On 08/09/2006, at 7:10 AM, Gavin Kistner wrote:

>
> local a = 10
> function f( )
> 	print( a )
> end
>
> local a = 20
> function g( )
> 	print( a )
> end -- g
>
> a = 30     -- no local here
> print( a ) --> 30
> f( )       --> 10
> g( )       --> 30
>


The surprising part here is that the last one prints 30 and not 20.  
However it is consistent with my forward declaration problem.

The last "a = 30" must have modified the *most recently declared* local variable, hence f prints 10 but g prints 30.

- Nick