lua-users home
lua-l archive

Re: Documenting Lua gotchas for newbies.

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


On Sat, Dec 04, 2010 at 08:29:58PM +0200, Hisham wrote:
> On Fri, Dec 3, 2010 at 3:53 PM, Javier Guerra Giraldez
> <javier@guerrag.com> wrote:
> > On Fri, Dec 3, 2010 at 12:39 PM, Hisham <hisham.hm@gmail.com> wrote:
> >> >From those uses, I see two sensible deterministic definitions for #,
> >> which would be either:
> >>
> >> * the number of elements in the table
> >
> > besides the "if #t == 0" (note we already have "if next(t)==nil"), i
> > don't see where this can be useful.  IOW: deterministic but useless
> 
> Having had to explain the behavior of # to a number of people who
> otherwise 'got' the rest of the language just fine (and looking at
> their stares and saying "yeah, I know") I would find the simplicity
> and determinism to be a big plus. 
Consider the following code and its result:
 a={1,2,3,nil,5}
 b={}; for i=1,5 do b[i]=a[i] end
 print(#a,#b)
5 3
The hard thing to explain is that a table can be an array, a dictionary 
(useful Python term) or both. And that in the above example b[5] 
belongs to the dictionary part, not the array part of a. Once you
have got that across to your newbie, the behaviour of # is not hard 
to explain. It is in fact a useful way of putting one's finger on 
the distinction.
I agree that there are many applications in which the cardinality
of a table is a necessary concept, but please don't change the meaning
of the hash. Backward-incompatible changes that cause existing 
programs to break are only allowable if truly unavoidable. Better 
have a function with a another name (table.size?) for the actual
number of objects in a table.
Dirk

AltStyle によって変換されたページ (->オリジナル) /