[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: A very basic thing I don't get
- From: Dirk Laurie <dpl@...>
- Date: Sat, 1 Oct 2011 21:52:44 +0200
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:
1. Arrays and lists are not part of the language.
2. Lua has only one data structuring mechanism: `table`.
3. A table is a map from "keys" to "values".
4. All Lua values except `nil` and `NaN` are keys.
5. Any Lua value can be a "value".
6. If you have not assigned a value to a key, the value `nil` is
associated with that key.
7. Whether a particular nil is actually stored, is an implementation
detail that does not concern the user.
8. The function `pairs` iterates over those (key,value) pairs for
which the value is not nil, in some undefined order.
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".
10. Those functions do not actually fail on tables that are not lists,
but their results are not as useful in those cases.
10. A set of keys like (1,2,3,5,7,8) is not in any way special, although
the abbreviated table constructor allows you to define such a set
with the aid of nil values.
11. Whether a particular nil is actually stored, is an implementation
detail that does not concern the user. (We've said this before,
but it is worth repeating.)
12. Whether the implementation of a particular table takes advantage
of the fact that it is in fact a list, is a detail that does not
concern the user.
Dirk