lua-users home
lua-l archive

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


>Lua loop counters are in their own local scope. I've known for some time,
>but now I really just want to know why.

Efficiency. The virtual machine that implements Lua contains a FOR instruction.
Otherwise, it would just be syntactic sugar for a while loop.

>If not, how hard would this be to change in my own no-longer-Lua branch?
>
>  i=999
>  for i = 1, 10 do
>    print(i)
>  end
>  print(i) -- prints 999

Just save the value of the loop variable in an outer (perhaps local) variable:

  local I
  for i = 1, 10 do
    print(i)
    I=i
  end
  print(I)

>  function f(a=1,b=2,c=3)
>    ...
>  end
>
>  f(c=999,a=0)

Try

  function f(t)
   local a,b,c=t.a,t.b,t.c
   ...
  end

  f{c=999,a=0}

Note the {} instead of () in the function call.

If you like named parameter then you won't mind the overhead of creating a
table for each function call.

>Finally, I can't remember specifically but wasn't there some unpopular
>global vs local default scope issue that was going to be changed?
>I think it was simply that local would be implicit instead of global.

The solution adopted in Lua 5.0 is that every function (including the "main"
function in each chunk) has its own table of globals, which can be changed.
With adequate metamethods set for these table of globals, you can have a
sort of implicit declaration of locals, flag writes to global variables,
and much more.
--lhf