lua-users home
lua-l archive

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

On 01/10/2011 21.52, Dirk Laurie wrote:
On Sat, Oct 01, 2011 at 08:43:02PM +0200, Stefan Reich wrote:
Well... I would generally say that I am not totally happy with the way
arrays and lists in Lua work. It's probably the only thing I would
change right now if I was to change something in the language.

I find the relation between nil and lists also confusing.

I have to say: Arrays in Lua are indeed a little confusing.

Only while you still think in some other language.

Think of it this way:

Very good summary of an often recurring topic!

Some additions for the archive:

   8. The function `pairs` iterates over those (key,value) pairs for
      which the value is not nil, in some undefined order.
Which is a sort of wrapper for the true iterator function "next"
   9. Since the particular set of keys (1,2,3,...,n) occurs very often in
      applications, Lua offers extra support for those.
      - the length operator `#`
      - the function `ipairs` which iterates over the (key,value) pairs
        in the well-defined order 1,2,3,...
      - the table library
      - the abbreviated table constructor with implicit keys
      It is convenient to call such tables "lists" or "arrays".
In Lua 5.2 the new terminology for those ones are "sequences" (see section 3.4.6 of refman)

  10. Those functions do not actually fail on tables that are not lists,
      but their results are not as useful in those cases.
In Lua 5.1 `#' was well defined also for non-sequences, albeit it didn't return a generally useful value. In 5.2 `#' is defined only for sequences. Although the old behaviour is still there for non-sequences, now is to be considered an implementation detail.

Note: as the aforementioned section 3.4.6 states, non-integer keys doesn't interfere with a table being a sequence, thus the following *is* a sequence:

{ 10, 20, 30, 'a', 'b', foo = 1, bar = 'hello!'}

(this may come up as unexpected for newbies or for people not reading the manual carefully, since the meaning of the term "sequence" in Lua is slightly different from the usual math meaning).



-- Lorenzo