lua-users home
lua-l archive

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

On Fri, Oct 3, 2008 at 11:07 AM, David Jones <> wrote:
>> Mapping Lua's lexical scope into JavaScript's function scope is easy,
>> rename the variables so the scopes don't clash, and fix the
>> references. It's even easier if you are compiling to a newer
>> JavaScript implementation and use let instead of var.
> As you discovered, the poster wanted the other way around.  But...
> Your proposal is easy, but it won't get closures correct.  Not even close.
> Consider: a={} for i=1,10 do a[i]=function()i=i+1;return i;end end
> It's a bit of annoying impedance match either way around.

Yeah, I should have payed more attention to my original answer, thanks
for pointing out my mistake! Alas, this makes implementing Lua in JS
even closer to implementing Lua on the JVM and CLR (which don't have
closures at all), and the implementation would be similar (having
cells to hold upvalues; been there, done that), at least for upvalues
inside loops. Good thing JS now has proper block scoping (thoug not
IE's JS, yet)!

A cleaner way is to compile all Lua loops to JavaScript functions (so
Lua's block scope becomes JS function scope). The function would have
the loop inside it (no tail-recursion, which is a whole other can of
worms :-) ).

Erik Meijer has a similar exaple of this problem in, but
comparing C# (which has closures with proper block scoping, as Lua)
with JS. C#'s closure implementation is more complex (using display
classes generated by the compiler) because of C#'s static typing, but
the essence is the same.

For JavaScript to Lua this doesn't matter, though, declaring all vars
in the beginning of the function and preventing name clashes will
implement the correct semantics.

> Cheers,
>  drj

Fabio Mascarenhas