lua-users home
lua-l archive

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



On 25-Nov-05, at 2:46 PM, Philippe Lhoste wrote:

I believe upvalues has a sense in Lua 4.0 and before, where you needed a special syntax to access local variables of upper scope. There was/is a thing with "captured (or frozen) value" with which I was never comfortable with, coming from a procedural world... I don't even know if this trick is still possible in the lexically scoped Lua.

I think that's true. "upvalues" in Lua 4.0 really were values (as are the residual upvalues in C closures in Lua 5).

If you really need to capture the current value of a variable (or an expression) in Lua 5, you need to do it explicitly, although you can reuse the variable name if you want to confuse your friends.

If I recall Lua 4 syntax correctly, it looked like this:

  local a = 3
  local function foo3()
    print(%a)
  end
  a = 4
  foo3()

--> would have printed 3, the value of a when captured.

Removing the % and running that in Lua 5, it will print 4, the value of a at the time foo3 is called.

You could achieve the old behaviour like this:

  local a = 3
  local foo3
  do
    -- Here's the confuse your friends bit
    local a = a
    function foo3()
      print(a)
    end
  end
  a = 4 -- this is not the same a as in foo3
  foo3()

I have to say that although once in a blue moon I find myself doing that, it's pretty rare, and I don't miss Lua 4's upvalues nearly as much as I thought I might when they were about to disappear.