lua-users home
lua-l archive

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

David Lam wrote:
> Edgar Toernig wrote:
> >No.  Local variables are kept on a stack and will not effect the GC.
> So any local string or table will be freed when you exit a function? That
> sounds good.

Variables are a place to store objects[1].  Whether the stored object
is a number or a table or anything else doesn't bother the variable.
And local variables are not garbage collected objects themselves.  So
you may use them without creating intermediate objects.  I think, that
was what the original poster meant.

About the objects stored within local variables: at the moment the local
var is no longer active the GC _may_ collect the object that was stored
there.  The actual freeing of the object has nothing to do with function
scopes or variable live times.  The GC runs at certain times and frees
all objects that are no longer accessible by any Lua code.

> >     for i=1,100 do  x="foo"..tostring(i)  end  -- 100 new strings
> What about if x is a declare a local? Will only the last string assign to x
> be free when the function exit? And the other 99 strings be GC?

No.  Nothing special is done at function exit.  All 100 strings will be
garbage collected some time later after the function has terminated.

> Same questions goes for table: So if I have
> function foo()
>         local x = {"a", "b", "c"}
>         x = {"d"}
> end
> {"d"} is free when the function exit and {"a", "b", "c"} will be GCed later?

Same as above.  Both tables are freed later by the GC.  It is the only
part of Lua that frees something and its policy is simple: free every-
thing that is not reachable.  And you can force a GC run by calling

Ciao, ET.

[1]: In fact, except for numbers it only holds pointers to the objects.