lua-users home
lua-l archive

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

On 15-Sep-04, at 5:58 PM, Tom Spilman wrote:

I'm using the first "5.1 (work)" release from a few months ago. Maybe this
is a change in 5.1?

Yes, that is correct, as I understand it.

 Looking thru the source in lparser.c fornum() does this...

  new_localvarliteral(ls, "(for index)", 0);
  new_localvarliteral(ls, "(for limit)", 1);
  new_localvarliteral(ls, "(for step)", 2);
  new_localvar(ls, varname, 3);

So it seems they made an explicit decision to not name "(for index)" with
the real index name.  It would be nice if this was corrected so I can
clearly tell which nested loop these automatic for locals correspond to.

The real index name is the last localvar; it is not in scope until the loop starts. Consequently, for loops correctly (imho) create a new index object
on each loop, which in turn means that upvalues work correctly.

In other words:

  timestable = {}
  for i = 1, 10 do
    timestable[i] = function(j) return i * j end

will do the right thing in lua 5.1, and something quite different
in earlier versions.

Although undocumented, it also means that the index variable can be
reassigned within the loop without changing the loop -- in 5.0, this
behaviour was "undefined". (Whether it will actually be defined in
5.1 is yet to be seen, but it is sometimes useful.)

It may be possible to make it look like the index variable is
actually in scope in the for statement itself (although that is
technically incorrect) but I haven't looked closely at the code.