lua-users home
lua-l archive

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


I assume you meant to include the mailing list in your reply (given your
closing), so I've added it back.

Thanks Diego, that was a good explanation. It made my brain a little
sore thinking about it, but I think I got it. :-)

-----Original Message-----
From: Diego Nehab [mailto:diego@tecgraf.puc-rio.br] 
Sent: Monday, May 14, 2001 9:43 PM
To: Curt Carpenter
Subject: Re: Local variables


Hi,

1: > function new_counter()
2: >   local count = {v=0}
3: >   return function ()
4: >       %count.v = %count.v + 1
5: >       return %count.v
6: >     end
7: > end

It works more or less as follows:

Line 2  creates a  table and makes  the local "count"  point to  it. The
table is  not created  on the stack,  but rather on  a global  heap, and
instead a reference to it is placed on the stack. The expression "{v=0}"
is  the  table constructor.  On  function  exit, the  reference  "count"
released,  but the  table object  remains on  the heap.  Only references
exist on the stack.

If the  local "count" was  the only reference  to that table,  the table
would be freed on the next garbage collection cycle.

Line 3-6 defines  a nested function. This function is  also allocated as
an object  on the heap,  at run-time, whenever "new_counter"  is called,
and a  reference to it is  returned to the callee  of "new_counter", who
can store it in a variable. If, at  some time, no references are left to
that function  which was returned  by "new_counter", than  that function
will also be collected.

Howerver, since that nested function  references 'the value of "count"',
which happens to  point to that table created by  line 2, this reference
is copied as a closure value in that nested function, when "new_counter"
is executed.

Therefore, as long as there is a reference to the nested function, there
will also  be a  reference to  the table of  line 2,  which will  not be
collected.

Each time  "new_counter" is  called, a  new table is  created and  a new
instance  of the  nested function  is created  that references  that new
table.  Therefore,  the  returned   counted  function  objects  will  be
completely independent.

Lua gurus, please correct me if I have sinned.

Regards,
Diego.