lua-users home
lua-l archive

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


On 17/11/11 00:12, Maximilian Herkender wrote:
[...]
> Coroutines are not yet supported, but they might be able to be recreated
> using web workers, otherwise it might be possible to fake them. I don't
> know enough about coroutines or web workers right now to say for sure.

They can't be --- coroutines all exist within the same Lua universe and
so can access each other's variables, while web workers exist within
different Javascript universes and can't (and can only communicate with
each other via messages).

The only way of doing coroutines would be to automatically invert the
control flow of the code, where, e.g., all Javascript code becomes
threaded via a dispatcher based around the Javascript event loop, so you
can return to the event loop at any point in the code. It's all quite
doable, but deeply non-trivial (particularly if you want it to be
efficient). OTOH it would be a killer feature. Javascript being
single-threaded is one of its major flaws... er, amongst its many major
flaws, this is one of them.

(ECMA were actually contemplating adding coroutines to a recent
Javascript version. They eventually decided not to, because it would be
'too complicated'. Pfah...)

[...]
> That way the block-level scoping in Lua will behave the same in every
> experiment I've tried. I'm not completely confident the behavior of
> variables is the same as in the Lua VM, but I haven't found anything
> that suggests it is different.

There's one big gotcha with Javascript vs. Lua when it comes to closures:

In Lua:

function main()
  for i = 1, 10 do
    local j = i
    f(function() print(j) end)
  end
end

...each closure passed to f gets a different j (with a different value).

In Javascript:

function main()
{
  for (var i = 1; i < 10; i++)
  {
    var j = i;
    f(function() { print(j); });
  }
}

...each closure passed to f gets the *same* j (which means that once
main() exits, it will have the value 10).

This is because Javascript variables are scoped at the function level,
regardless of where the var statement actually is.

-- 
┌─── dg@cowlark.com ───── http://www.cowlark.com ─────
│
│ "Never attribute to malice what can be adequately explained by
│ stupidity." --- Nick Diamos (Hanlon's Razor)

Attachment: signature.asc
Description: OpenPGP digital signature