lua-users home
lua-l archive

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



Roger D. Vargas wrote:
I know it is in the manual, but seems that I dont clearly underestand it. So can somebody explain me what are upvalues and closures?

In Damian Conway's words:

  A closure is just a function that refers to one or more lexical
  variables declared outside the function itself.

There is a Lua 5.0 example here:
http://lua-users.org/lists/lua-l/2003-06/msg00059.html

Prior to Lua 5.0, Lua didn't have lexically scoped variables. Instead Lua had upvalues which are just read-only values copied from local variables and stored within the function. The same example in Lua 4 requires the extra %

$ cat closure.lua

do
  local name = 'bob'

  function print_name()
    print('name', %name)
  end
end
-- cannot access name directly from here on,
-- but print_name has a read-only copy of name's value
print_name()

$ bin/lua -v closure.lua
Lua 4.0.1  Copyright (C) 1994-2000 TeCGraf, PUC-Rio
name    bob


The only change in the C API between Lua 5 and 4 -- as far as upvalues are concerned -- is the upvalues for C-closures are at virtual stack indexes given by lua_upvalueindex(i) instead of being pushed on the stack after the function arguments. Also you can now access and alter the upvalues with lua_getupvalue and lua_setupvalue.

- Peter