lua-users home
lua-l archive

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



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
>