[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: String indexing again
- From: Dirk Laurie <dpl@...>
- Date: Mon, 20 Dec 2010 15:58:49 +0200
On Mon, Dec 20, 2010 at 02:35:09PM +0200, Randy Kramer wrote:
> For those of us (maybe just me) just starting to watch from the peanut
> gallery, without the long lecture, can you tell me what s[3] does
> indicate--I mean what does the s function (is it a function?) do?
>
> On Sunday 19 December 2010 11:57:19 pm Dirk Laurie wrote:
> > Except for the long lecture you need to explain why you get this:
> > > s='hello'; print(s[3])
> >
> > nil
Indexing for strings was not defined at all in Lua 5.0:
--
Lua 5.0.3 Copyright (C) 1994-2006 Tecgraf, PUC-Rio
> s='hello'; print(s[3])
stdin:1: attempt to index global `s' (a string value)
stack traceback:
stdin:1: in main chunk
[C]: ?
--
It is still not defined in Lua 5.1 and 5.2. But in the meantime,
strings have acquired a metatable, in order to allow you to write
s:sub(3,3) instead of string.sub(s,3,3). Since indexing for
strings is not defined, s[3] falls through to the metatable,
which does not have an entry with key value 3. Therefore, as
with all table references, nil is returned.
In my opinion, this sort of non-intuitive behaviour, which needs
very careful reading of the reference manual to understand, is
a much greater evil than the alleged illogic and Cobol-likeness
of making s[3] mean the third character of the string s. But
I promised to stop ranting about this.
Dirk