[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Simple function (re)compilation?
- From: Miroslav Janíček <mira.janicek@...>
- Date: Thu, 6 Oct 2016 15:43:02 +0200
> 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.