lua-users home
lua-l archive

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


Would this change from Lua 5.1 apply to "for k,v in <function> do end" and other variations of 'for' as well or just to the version with numeric limits?
Thanks,
Alex 
-----Original Message-----
From: RLake@oxfam.org.pe [mailto:RLake@oxfam.org.pe]
Sent: Wednesday, May 12, 2004 5:16 PM
To: Lua list
Subject: Re: Closures


Jack Christensen preguntó:

> I'm getting some results I was not expecting with this code.

> functionList = {}
> for i=1, 10 do
>   functionList[ i ] = function()

>      print( i )  
>   end
> end

> for i=1, 10 do
>   functionList[ i ]()
> end

> I get ten 10's printed out. As I understand closures I would have
> expected 1 to 10. Could someone enlighten me as to what is wrong?

I agree. Fortunately, this odd behaviour is slated to change
in Lua 5.1. (see below)

There is nothing wrong with your understanding of closures. It is
the implementation of the "for" loop which you have gotten wrong;
in effect, the loop is:

  local i = 1
  while i < 10 do
    ...
    i = i + 1
  end

As opposed to:

  local _control_ = 1
  while _control_ < 10 do
    local i = _control_
    ...
    _control_ = _control_ + 1
  end

------> results from Lua 5.1 ----->

Lua 5.1 (work)  Copyright (C) 1994-2004 Tecgraf, PUC-Rio
> functionList = {}
> for i = 1, 10 do
>>   functionList[i] = function() print(i) end    
>> end
> for i = 1, 10 do functionList[i]() end
1
2
3
4
5
6
7
8
9
10
>