[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Problem with global variables
- From: Philippe Lhoste <PhiLho@...>
- Date: Thu, 25 Jul 2002 14:31:01 +0200 (MEST)
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
Obiviously, when I declare the List function, it takes a snapshot of the
global values used inside it and uses them instead of the current value.
1) I though it was only true for local values;
2) Using upvalue %globalVar doesn't change anything on Lua 4.0 and generates
a warning on Lua 5.0;
3) I though this problem was lifted in Lua 5.0.
Of course, I can give globalVar as parameter to List, but my initial code
used foreach, where I cannot do that.
Oh, OK. I never really got around this for syntax...
>From the manual: "The variable var [loop counter] is local to the statement;
you cannot use its value after the for ends." And for what it is worth,
neither on a an external function! (?)
So the correct form of my program is:
for k = 0, 2 do
print("Entry #" .. k)
globalVar = k
for i, v in aTable do
List(i, v)
end
end
Since I have found the solution of my own problem, this e-mail is already
obsolete, but I send it anyway, because it can help other newbies...
Is it normal the problem persists in Lua 5.0?
Regards.
--
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--
Philippe Lhoste (Paris -- France)
Professional programmer and amateur artist
http://jove.prohosting.com/~philho/
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net