lua-users home
lua-l archive

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


> On 6 Oct 2016, at 15:16, Rodrigo Azevedo <rodrigoams@gmail.com> wrote:
> 
> Given the code:
> 
> f = function ()
>         local o = 10
>         return
>                 function(x) return x+o end
> end
> 
> local o = 10
> g = function ()
>         return
>                 function(x) return x+o end
> end
> 
> print(f(),f(),g(),g())
> 
> It prints:
> 
> function: 0x2196ff0    function: 0x21965f0    function: 0x2196da0    function: 0x2196da0
> 
> The problem:  Why f() returns different functions while g() does not?

This is a small optimisation that “caches” closures.

The inner functions use a parameter ‘x’ and an upvalue ‘o’. You can think of an upvalue as a reference to a variable. Now, in ‘f’, the variable ‘o’ is local to ‘f’, so every time you call f(), you get a new ‘o’. In ‘g’, the ‘o’ is itself an upvalue: every time you call g(), ‘o’ is the same variable you’re referring to.

Since all functions you return from ‘g’ will refer to the same upvalue ‘o’, they can all be considered equal. (The parameter ‘x’ doesn’t influence this.)

The interpreter exploits this fact, and only instantiates the closure once.

Hope it helps!

  M.