lua-users home
lua-l archive

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



Well, this turns out to be yet another reason for redefinable __len. That way, one could have tables whose # operator counts from zero.

-asko


Greg Falcon kirjoitti 9.8.2007 kello 18:29:

On 8/9/07, Paul Ducklin <duck@roaming.ath.cx> wrote:
Lua's 1-based native indexing
already annoys people

Errrr, which people exactly?

The former is just an unnatural idiom forced on C
coders because that's how C works.

Okay, I'll bite.  I'd agree that's it's an unintuitive idiom, but it's
not unnatural.  This issue is discussed in depth on the wiki at
http://lua-users.org/wiki/CountingFromOne.  (There's a link on that
page to a short essay by Dijkstra which pretty clearly states the
argument, if you don't want to read through the pages of text.)

The idea is that, when using integer ranges in algorithms, the
half-open representation has a lot of nice properties.  Once you
accept that, the only question is whether to represent the indices of
an N-element array as [0, N) or [1, N+1).

That said, I wouldn't characterize myself as "annoyed".  It really is
a very minor issue, since 0 is a valid table key, and the heavy
algorithmic lifting can often be done in the host app.  Also, Lua's
aim of being an embedded language means the people who write code in
it are more likely to not be computer-science types.  Making a less
theoretically pure but more intuitive language design choice here is
perfectly reasonable.

The only problem with trying to use 0-based indexing in Lua (besides
the minor inefficiency of storing the "first" entry in the hash part)
is that the # operator reports {[0]=42} and {} as having the same
length.  But the thing I take away from this huge thread is that the #
operator likes making trouble.  ;)

Greg F