lua-users home
lua-l archive

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

On Thu, Nov 11, 2004 at 10:11:34PM -0800, Quinn Tyler Jackson wrote:

> What is the expected output of the following snippet if the function
> returned by get_function is a closure?
> k = 0;
> function n(x)
>    k = k + 1;
>    return x + 10;
> end
> function get_function(x, y)
>      return
> 	     function (y)
> 		    z = n(x);
> 		 end;
> end
> f = get_function(100, 100);
> f(100);
> f(110);
> print ("n called " .. k .. " times");

Quinn, I can answer that without even looking at the declaration of
get_function() nor its call nor the two applications of f().  The
reason is that nothing touches "k" except function n(), and therefore
if n() were actually closed in respect of its free variable k then its
internal closed "k" would refer to an entirely different "k" than the
final print statement reads and prints out.

Consequently, if Lua created genuine closures, your code would print out:

                         n called 0 times

Here in Lua it doesn't, instead it finds that k has a value of 2 because
n(x) was called twice and hence it incremented its free (not closed)
variable k twice.

The example above doesn't attempt to make use of any closed internal k
that a Lua with closures might have created.  To do so, it would need
to use the k in its output expression, eg. "return x + 10 * k;".  This
k would be bound tightly to function n for the full lifetime of n, so
you could invoke n() repeatedly and the closed k would keep incrementing.

That's not the outer k though.  The outer k merely sets the value of the
initial closed k in the closure.  Or I should say, "would" set it. :-)

Rich Artym.
Existing media are so disconnected from reality that our policy debates
spin around a fantasy world in which the future looks far too much like
the past.