Fabio Mascarenhas | 3 Oct 17:20
Favicon

Re: JavaScript to Lua compiler

On Fri, Oct 3, 2008 at 11:07 AM, David Jones <drj <at> ravenbrook.com> 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
http://research.microsoft.com/~emeijer/Blog/LookClosure.html, but
(Continue reading)


Gmane