lua-users home
lua-l archive

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

As part of a long-term project to teach myself more about compilers,
I've been working on a programming language. Right now I'm looking at
upvalues and closures.

It turns out that the naive approach to handling upvalues --- where the
closure stores a references to the defining function's stack frame, and
then the upvalues are stored in the stack frame --- works perfectly well
but gives Javascript upvalue semantics:

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

Every closure created in the call to f gets a reference to the *same*
j, which means that once main() has exited it will have value 10.

I much prefer Lua semantics:

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

Each closure here gets a *different* j. To me, this is vastly more
intuitive (and more useful). So I'd prefer to implement this one.

So, firstly: does this difference in behaviour have an actual name, so I
can refer to it and hope that people understand what I'm talking about,
and can anyone point me at any analysis of how it works --- in
particular, how the compiler decides when to allocate a heap block to
store the upvalue in? (Because obviously, we now need multiple heap
blocks per stack frame rather than just one.)

┌─── ───── ─────
│ "Never attribute to malice what can be adequately explained by
│ stupidity." --- Nick Diamos (Hanlon's Razor)

Attachment: signature.asc
Description: OpenPGP digital signature