lua-users home
lua-l archive

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


On Tue, Jun 14, 2011 at 06:05:17PM +0200, Florian Weimer wrote:
> * Xavier Wang:
> 
> > in beta:
> 
> | The length of a table t is only defined if the table is a
> | *sequence*, that is, all its numeric keys comprise the set *{1..n}*
> | for some integer *n*. In that case, *n* is its length.
> 
> So it is no longer advisable to store something in t[0] if you want to
> use #t?  Would it be possible to change that to "positive numeric
> keys", at least?
> 
The present implementation makes #t well-defined and equal to n if all 
its positive integer keys comprise the set {1..n}.  That would not be
a problem.

However, table.insert and table.replace may behave strangely if there 
are some numeric keys not in the range 1..n, even if they are negative.
For example (these appeared in previous posts on 5.2 alpha):

> t={1,2,3}
> table.insert(t, -1e8, 'x')    -- takes a long time
> for k=1,#t do print(k,t[k]) end

> t={1,2,3}
> table.insert(t, -1e-8, 'x')   -- This is not an integer key
> for k=1,#t do print(k,t[k]) end

In both cases, the printout on my machine is:

1   nil
2   1
3   2
4   3

So inserting something at a negative key destroys the list-ness
of the table.

> t={1,2,3}; k=-42; table.insert(t,k,1); table.remove(t,k)
> for i in pairs(t) do print(i) end
2
3
4
-42

So you can't remove something you inserted.

The beta documentation says:
> Currently, all functions in the table library assume that the table 
> represents a list. In particular, they all ignore non-numeric keys 
> in tables given as arguments. 

It carefully says nothing about what happens when there are numeric
keys that destroy the list property.  It could explicitly have said
that the behaviour in such a case is undefined.

And, it leaves the door open for future versions that may operate on 
non-lists.

Dirk