lua-users home
lua-l archive

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


In 4.1 you can use tables with weak keys to memoise functions of arbitrary objects (this would be an example of a memoised function,
albeit not strictly a function in the functional programming sense). I think that's a highly appropriate use of weak tables.

However, in 4.0 this facility doesn't exist, so your only alternative would be to write it in C using weak references. If you were
going to do that, you could write your own vector type (it's easy enough if you don't worry too much about garbage collection
problems -- unfortunately, there is no way that a userdata can participate in Lua garbage collection. Well, that's not true -- I
have a proposed solution -- but out of the box and compliant with the published API there's no way of doing it.) Putting glue around
your vectors is probably a better idea.

I banged up a little example of that, if anyone wants to see it. I left it at <http://lua-users.org/wiki/VectorGlue>

The thing to remember is that Lua doesn't have lists (or vectors). It has tables. You can emulate a list (or vector) using a table
with restricted keys. As in any implementation of a vector, you need somewhere to put the size of the vector, and since the building
block of Lua is tables, they use a key.

I still think that putting non-integer keys in a table emulating a vector is poor programming style (although I have already
confessed to doing it.)

Luiz Carlos Silveira wrote:

> > But the "n" is not the size of the table. It's a key in a
> > particular type of
> > table which is used to provide the functionality of vectors.
>
> The computation time saved by the usage of this .n field in my programs is surely much less than the time that it took me to
> discover some very-hard-to-find bugs caused by this field.
>
> I believe that everyone would agree that it would be better if this .n field wasn't there. (If I remember correctly, the only
> purpose of a .n field was to speed up the insertion operation, wasn't it?)
>
> I don't know too much about garbage collection issues, but a nearly perfect solution would be if these 3 functions could share a
> table. Something like this:
>
> N_TABLE = {}
> function getn(t)
>         if (N_TABLE[t] == nil) then
>                 N_TABLE[t] = count_elements(t)
>         end
>         return N_TABLE[t]
> end
>
> and equivalent for tinsert and tremove.
>
> Possibly, to ease flexibility, another function might have to be introduced: setn(t)
>
> The question is: none of the tables stored in the N_TABLE could be collected, could them?