lua-users home
lua-l archive

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


On Jun 1, 2013, at 7:24 AM, Dirk Laurie wrote:

>  When called with
> an anonymous table, e.g.
> 
>   myfunc{1,2,3,4,5}
> 
> it is OK to modify the table and return it, but when called with
> a table that already has a name, one must make a new copy
> in case that name is referenced later.
> 
> Is there a way of diagnosing this difference?

No. Values do not have names; variables do.

I think you want something else: Do I hold the last reference to this table?

This is very useful knowledge in some situations. The MOO language's lists (and strings) are immutable. The language defines mutation-like syntax as sugar for creating fresh lists. So

  lst[1] = 2;

is the same as

  lst = listsub(lst, 1, 2)

If lst is, for example, 16384 elements long--perhaps to contain Apple II firmware or something--the simple implementation involves cloning lst, mutating the copy, setting the variable, and freeing the old lst if no other references exist. So setting all of the elements is O(n^2) since the list is copied n times.

Ben Jackson implemented a bunch of optimizations to recognize this situation and mutate lst in place if it's the last reference. Note that in loop bodies, if you didn't have the last reference initially, you will have the last reference after the first iteration's copy.

I came across another situation where this is useful: lazy XML->LOM parsing. If a program drops the last reference to a subtree, any remaining XML yet to be parsed in that tree cannot affect the future of the program. The XML parser can go into a fast-forward mode, lexing but ignoring the contents of everything until the close tag. http://lua-users.org/wiki/LazyKit (although I probably should see if I have a releasable 5.2 version of that nine-year-old code....)

I don't know how expensive it would be to ask for the GC's help in answering "is this the last reference". This is one of the few times reference-counting implementations win.

Jay