lua-users home
lua-l archive

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


I seem to remember that the variables used in a 'for' statement are
automatically declared locals, whose scope is limited to the 'for' body.
Therefore in your loop, the local globalVar is used as the loop index, but
in your function List(), it is the global one that gets referenced. Me
thinks this explains the behaviour you are observing :-)

Cheers,

Benoit.

> -----Original Message-----
> From: Philippe Lhoste [mailto:PhiLho@gmx.net]
> Sent: jeudi 25 juillet 2002 14:31
> To: Multiple recipients of list
> Subject: Problem with global variables
> 
> 
> Ha, I though I was starting to understand how closures, upvalues and
> variable scope was working on Lua, and I stumble upon a 
> puzzling problem.
> 
> Reduced to a simple form, I have the following code:
> --%<-----
> globalVar = 100
> aTable = { "a", "b", "c", "d" }
> 
> function List(i, val)
>   print(globalVar, i, val)
> end
> 
> for globalVar = 0, 2 do
>   print("Entry #" .. globalVar)
>   for i, v in aTable do
>     List(i, v)
>   end
> end
> ----->%--
> The result, both on Lua 4.0 and Lua 5.0 is:
> Entry #0
> 100     1       a
> 100     2       b
> 100     3       c
> 100     4       d
> Entry #1
> 100     1       a
> 100     2       b
> 100     3       c
> 100     4       d
> Entry #2
> 100     1       a
> 100     2       b
> 100     3       c
> 100     4       d