lua-users home
lua-l archive

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


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 specification of that type of table is somewhat incomplete; it does not say
whether non-integer keys will be tolerated or perhaps used in an
implementation-dependent way. Although I too have been guilty of combining
vectors and other information in tables, it's probably not good programming
style.

The actual implementation does not handle non-integer keys or negative keys in
an intuitive way. If there is no key "n" in the table, getn returns the integer
cast of the largest non-negative numeric key in the table.

    Lua 4.0  Copyright (C) 1994-2000 TeCGraf, PUC-Rio
    > t = {3, 4; [99.7]=2}
    > print(getn(t))
    99
    >

I don't regard this as a bug, though. The table t in the above example is an
incorrectly formed vector.

Good programming style probably would be to limit yourself to the vector
primitives (tinsert, tremove, etc.) when using vectors.

It is an interesting fact that "n" is simply a key with a value. It provides the
interesting ability to "shrink" a vector by setting the key "n" to some value,
and later "expand" the vector back to its original values. That ability does
seem to be guaranteed by the language specification.

If you want to hide all the implementation details of vectors, write a
class-wrapper around the Lua implementation.

Just my S/0.02

Rici
-----------

P.S.

The lack of a primitive which actually tells you the size of a table is a little
annoying, but it is easy enough to define:

function howmany(t)
  local i = 0
  for k, v in t do i = i + 1 end
  return i
end


John Passaniti wrote:

> > Is there any chance that the table entry used to
> > store the number of elements, ie. n, can be
> > renamed to something less likely to cause a name
> > clash with user code?
> >
> > eg. _n or __n__
>
> How about not giving it a name at all, but rather making it a hidden
> property of a table?  Then, if you want to get to the value, one would call
> a function like getn(table).  I wonder how much existing code that would
> break-- that is, how many people use table.n as a rough synonym for getn()?
>
> No matter what name you pick, *someone* will eventually toss data in a table
> that's the same name as this variable.  I love Lua, but this is one of my
> pet peeves of the language.  The size of a table should be an intrinsic
> property of the table-- not a member of the table.  I can see the value of
> making it optional-- but not the value of making it a member.